Leetcode 283, Move Zeros

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.

inplace的改变一个list,首先要想到的就是可能用two pointers。每次遇到一个非零的nums[j], nums[i]和nums[j]交换,然后 i 指针右移一步

 

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        if not nums:
            return []
        
        n = len(nums)
        ind = 0
        for i in range(n):
            if nums[i] != 0:
                nums[i], nums[ind] = nums[ind], nums[i]
                ind += 1

 

posted @ 2016-12-16 10:21  lettuan  阅读(85)  评论(0编辑  收藏  举报