283. Move Zeroes(难度:Easy)
描述: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.
举例:
输入:[0,1,0,3,12]
输出:[1,3,12,0,0]
注意事项:
- You must do this in-place without making a copy of the array. 不能拷贝或者更改数据的大小(即内存地址必须始终一直)
- Minimize the total number of operations. 需要数字最小的移动次数
解决方法一:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
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
解决方法二:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
count=nums.count(0)
nums[:]=[i for i in nums if i != 0]
nums+=[0]*count