https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/28/
Given an array nums , write a function that moves all to the end of the 0 array while maintaining the relative order of the non-0 elements.
Example:
[0,1,0,3,12][1,3,12,0,0]
Description
- You must operate on the original array, and you cannot copy additional arrays.
- Minimize the number of operations.
This topic has two ideas:
1. Using a similar bubble sort idea, from backward to forward, if you encounter 0 will put 0 and the back of the digital exchange position, until the last available location (need to record). Time complexity is O (n^2), Space complexity is O (1)
1 classsolution (object):2 defmovezeroes (Self, nums):3 """4 : Type Nums:list[int]5 : Rtype:void does not return anything, modify Nums in-place instead.6 """7Index_range =Range (len (nums))8Reverse_index_range = index_range[::-1]9Available_location = Len (nums)-1Ten forIinchReverse_index_range: One ifNums[i]! =0: A Continue - Else: -j = i + 1 the whileTrue: - ifJ >available_location: - Break -temp = Nums[j-1] +NUMS[J-1] =Nums[j] -NUMS[J] =Temp +j = j + 1 AAvailable_location-= 1
2. Traverse for the first time, all the non-0 values are moved to the front, the idea of compression; traverse the second time, and set the remaining space after the previous compression to 0. Time complexity is O (N), spatial complexity is O (1)
1 classsolution (object):2 defmovezeroes (Self, nums):3 """4 : Type Nums:list[int]5 : Rtype:void does not return anything, modify Nums in-place instead.6 """7Available_location =08 forIinchRange (len (nums)):9 ifNums[i] = =0:Ten Continue One Else: ANums[available_location] =Nums[i] -Available_location + = 1 - forIinchRange (Available_location,len (nums)): theNums[i] = 0
Leetcode Move Zero