Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
The digits are stored such that the most significant digit is at the head of the list.
Example
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Hint
You must do this in-place without making a copy of the array. Minimize the total number of operations.
Answer
solution:
classSolution(object):defmoveZeroes(self,nums):""" :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""" z =0for i inxrange(len(nums)):if nums[i]: nums[z],nums[i]=nums[i],nums[z] z +=1
因为i要从0开始到list长度,所以用for循环。for i in xrange(len(nums)):注意在思考部分对换操作是用nums[i],nums[i+1]=nums[i+1],nums[i],这里需要留心到for会自动增长i,因此不用i+1了,发挥双指针优势,从而帮助编程中的抽象。(我在编程时一直使用i+1与i对换,从而导致程序无法抽象出来的错误。切记。)