给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:
输入: nums = [0]
输出: [0]
咱就是说算法意识还是比较弱
一上来就用pop这样的方法
结果肯定不好
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
for l in range(length-1,-1,-1):
if nums[l] != 0:
continue
else:
nums.pop(l)
nums.append(0)
看了一下评论区里面大家主要都是使用双指针的方法
- 首先用指针1历遍数数组里的非零元素
- 指针2记录非零元素最后的位置
- 把非零元素都推到前面
- 根据指针2记录的位置把后面的元素都赋值0
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k = 0
for l in range(length):
if nums[l] != 0:
nums[k] = nums[l]
k = k + 1
while(k < length):
nums[k] = 0
k = k + 1