问题描述
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
解决方案
1.最快的原地置换
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero = 0
for i in range(len(nums)):
if not nums[i] == 0 and zero <= i:
nums[i], nums[zero] = nums[zero], nums[i]
zero += 1
2.使用remove+append
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count = 0
while 0 in nums:
nums.remove(0)
count+=1
for i in range(count):
nums.append(0)
3.先覆盖,再写入0
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count = 0
for i in range(0, len(nums)):
if (nums[i] != 0):
nums[count] = nums[i]
count += 1
for j in range(count, len(nums)):
nums[j] = 0
原文地址:https://www.cnblogs.com/huang-yc/p/10306676.html
时间: 2024-10-14 00:55:48