
image.png
一道簡單的原地題目,指直接在給定的數(shù)組上修改數(shù)值求解,不要復制到新的數(shù)組。
- 思路:解題思路
定義一個慢指針slow,初始化為0,表示非零元素的位置。
定義一個快指針fast,初始化為0,表示遍歷數(shù)組的位置。
使用一個循環(huán),從頭到尾遍歷數(shù)組nums。
在循環(huán)中,如果快指針指向的元素不等于0,就將它賦值給慢指針指向的位置,然后將慢指針向后移動一位。
在循環(huán)結束后,將慢指針后面的所有元素都置為0。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
# dual p
sp=0
fp=0
l=len(nums)
# n=0
# for i in range(len(nums)):
while fp<l:
#注意下面兩個while也要判斷fp是否小于l, 否則會產(chǎn)生數(shù)組越界的問題
while fp<l and nums[fp]==0:
fp+=1
# n+=1
while fp<l and nums[fp]!=0:
nums[sp]=nums[fp]
sp+=1
fp+=1
while sp<l:
nums[sp]=0
sp+=1
return nums

image.png