# 283. Move Zeroes *

60人阅读 评论(0)

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

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：54533次
• 积分：3842
• 等级：
• 排名：第8588名
• 原创：332篇
• 转载：90篇
• 译文：0篇
• 评论：11条
最新评论