The Idea: We can solve this problem purely using iterators and swaps. The general idea is to swap each zero with the first instance of the next number, given that the zero follows the number. Both iterators begin at 0. We continue to increment the left iterator until we find a zero, do so the same with the number iterator. Given that the number and the zero is found and that the zero follows the number, we can swap the two. This way, we preserve the order of the numbers
Complexity: O(n) time (since both iterators do a single scan through the array at most) and O(1) space
classSolution:defmoveZeroes(self,nums):""" :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ifnot nums:return zero_i =0 number_i =0 size =len(nums)# idea: swap with the first instance of the next numberwhileTrue:# increment to next zerowhile zero_i < size and nums[zero_i]!=0: zero_i +=1# implies that we scanned and didnt find zeroif zero_i >= size:return# increment to the next numberwhile number_i < size and nums[number_i]==0: number_i +=1# implies that we scanned and didnt find numberif number_i >= size:return# number is in front of the zero, so just move on# because a swap wont bring the zero forwardif zero_i > number_i: number_i +=1continue# swap nums[zero_i], nums[number_i]= nums[number_i], nums[zero_i]