python--leetcode 283. 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.

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

这一题就是给你一个list,里面都是数字,让你在不新开list的情况下,把0全部移到最后,并最小化操作次数。

O(n)复杂度内能解决,遍历一遍list就行,无非是list的操作。

代码:

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        i,count=0,0
        while(i
或者直接互换位置,用zero记录零的位置:

def moveZeroes(self, nums):
    zero = 0  # records the position of "0"
    for i in xrange(len(nums)):
        if nums[i] != 0:
            nums[i], nums[zero] = nums[zero], nums[i]
            zero += 1



你可能感兴趣的:(python)