题目:给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。必须在不复制数组的情况下原地对数组进行操作。
思路:
遍历整个列表,找到数组中的0,就将其删除,并对0的个数进行计数,最后把对应个数的0加入列表末尾。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
m = 0
i = 0
while i < len(nums):
if nums[i] == 0:
m += 1
nums.pop(i)
else:
i += 1
nums.extend([0] * m)
return nums
sol=Solution()
nums=[0,1,0,3,12]
print(sol.moveZeroes(nums))
注意:不能用for循环,for i in range(len(nums))因为使用pop删除的时候,会导致nums长度缩短,引起索引错误。
题解改进:
思路:双指针
使用双指针,左指针指向当前已经处理好的序列的尾部,右指针指向待处理序列的头部。
右指针不断向右移动,每次右指针指向非零数,则将左右指针对应的数交换,同时左指针右移。
注意到以下性质:
- 左指针左边均为非零数;
- 右指针左边直到左指针处均为零。
因此每次交换,都是将左指针的零与右指针的非零数交换,且非零数的相对顺序并未改变。
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
n = len(nums)
left = right = 0
while right < n:
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1