Move Zeroes

题目描述

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

解题方法

跟sort color方法一样

Solution

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        if length == 0:
            return 

        left, numNonZero = 0, 0
        while left < length:
            if nums[left] != 0:
                tmp = nums[numNonZero]
                nums[numNonZero] = nums[left]
                nums[left] = tmp
                numNonZero += 1
                left += 1
            else:
                left += 1