python--leetcode 283. Move Zeroes

来源:互联网 发布:php中不等于符号 编辑:程序博客网 时间:2024/06/06 13:26

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<len(nums)):            if(nums[i]==0):                del nums[i]                nums.append(0)                i=i-1            i=i+1            count=count+1            if(count==len(nums)):breaks=Solution()a=[0,2,0,1,0]print(s.moveZeroes(a))print(a)
或者直接互换位置,用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



原创粉丝点击