题目:
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:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
题意:
把给定数组中的0移动到最后。
注意原地移动,不能复制数组。最小化操作步数。
方法一:性能185ms
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
c = nums.count(0)
while c:
del nums[nums.index(0)]
nums.append(0)
c -= 1
方法二:性能66ms
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zeros = 0
safe = 0
for n in nums:
if n != 0:
nums[safe] = n
safe += 1
else:
zeros += 1
for i in range(zeros):
nums[safe] = 0
safe += 1