283. Move Zeroes *

来源:互联网 发布:ugnx是什么软件 编辑:程序博客网 时间:2024/06/09 17: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

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

https://discuss.leetcode.com/topic/32632/a-95-26-beat-rate-solution/5

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


0 0