给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
- 执行用时为 36 ms 的范例
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)
z = 0
i = 0
while i + z < n:
if nums[i] == 0:
z += 1
del nums[i]
else:
i += 1
while z > 0:
nums.append(0)
z -= 1
- 执行用时为 40 ms 的范例
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i] !=0:
nums[j], nums[i] = nums[i], nums[j]
j +=1
最多提交
- 执行用时为 44 ms 的范例
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
total = len(nums)
none_zero = 0
for i in nums:
if i == 0:
continue
nums[none_zero] = i
none_zero += 1
for i in range(none_zero, total, 1):
nums[i] = 0
- 48ms
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
i = 0
j = 0
while i < length and j < length:
if nums[i] != 0:
i += 1
j = max(i, j)
elif nums[j] == 0:
j += 1
else:
nums[i], nums[j] = nums[j], nums[i]