题目描述
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
思路1
- 遇到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.
"""
if len(nums)<=0:
return []
count=0
i=0
while i<len(nums):
if nums[i]==0:
nums.pop(i)
count+=1
else:
i+=1
while count>0:
nums.append(0)
count-=1
return nums
思路2
- 设置快慢指针,快指针先走,如果非0,则将所指的数传给慢指针
- 在末尾补0
ps: 相比于第一种思路,没有了删除的步骤,只是覆盖,快了不少
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
if len(nums)<=0:
return[]
j=0
for i in range(len(nums)):
if nums[i]!=0:
nums[j]=nums[i]
j+=1
for k in range(j,len(nums)):
nums[k]=0
return nums