283. Move Zeroes *

原创 2016年08月28日 15:31:23
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


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

<LeetCode OJ> 283. Move Zeroes

283. Move Zeroes My Submissions Question Total Accepted: 40008 Total Submissions: 94323 Difficul...

(数组)leetcode 283:Move Zeroes

(数组)leetcode 283:Move Zeroes

【LeetCode-283】Move Zeroes(C++)

题目要求:        给出一个数组,要求写一个函数把数组中所有的0全部挪到数组的最后面,同时保持数组中非0元素的顺序不变。比如给出一个数组nums=[0,1,0,3,12]。调用函数之后nums变...

leetcode-283. Move Zeroes c语言

1、来源:点击打开链接 2、题目: Given an array nums, write a function to move all 0's to the end of it while ma...
  • tzh476
  • tzh476
  • 2016年07月20日 07:49
  • 245

[Leetcode 283]Move Zeroes

题目描述: Given an array nums, write a function to move all 0's to the end of it while maintaining th...

LeetCode之路:283. Move Zeroes

LeetCode之路:283. Move Zeroes 一、引言一看到这道题,我就想起了曾经在西安一家公司面试的时候,一位面试官问我的一道题: 在一个数组中,零散的分布了一些正整数和 0,你可以写...

Leetcode—283Move Zeroes

题目:Given an array nums, write a function to move all 0’s to the end of it while maintaining the rela...

283. Move Zeroes

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relativ...

LeetCode 283 Move Zeroes(移动所有的零元素)

翻译给定一个数字数组,写一个方法将所有的“0”移动到数组尾部,同时保持其余非零元素的相对位置不变。例如,给定nums = [0, 1, 0, 3, 12],在调用你的函数之后,nums应该变为[1, ...
  • NoMasp
  • NoMasp
  • 2015年12月26日 19:07
  • 4052

leetcode note--leetcode 283. Move Zeroes

283. Move Zeroes   Given an array nums, write a function to move all 0's to the end of it while ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:283. Move Zeroes *
举报原因:
原因补充:

(最多只允许输入30个字)