卖萌的弱渣

I am stupid, I am hungry.

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:

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

Solution

(Move-Zeroes.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        index_zero = 0
        index_Nzero = 0
        while index_Nzero < len(nums) and index_zero < len(nums):
            # find zero pos
            while index_zero < len(nums) and nums[index_zero] != 0:
                index_zero += 1

            if index_zero == len(nums):
                return

            # find non-zero pos after zero pos
            index_Nzero = index_zero+1
            while index_Nzero < len(nums) and nums[index_Nzero] == 0:
                index_Nzero += 1

            if index_Nzero == len(nums):
                return

            nums[index_Nzero],nums[index_zero] = nums[index_zero],nums[index_Nzero]
        return