Leetcode's Move Zeroes (283)


given an array nums, write a function to move all 0 to the end of the array, while Keep the relative order of non-zero elements.


输入: [0,1,0,3,12]
出出: [1,3,12,0,0]


  1. must operate on the original array, can not copy additional arrays.
  2. Try to reduce the number of operations.

Python code:

class Solution(object):
    def moveZeroes(self, nums):
        j = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[j] = nums[i]
                j += 1
        nums[j:] = [0]*(len(nums)-j)