移动零--快慢指针算法

2023-04-23  本文已影响0人  HellyCla
image.png

一道简单的原地题目,指直接在给定的数组上修改数值求解,不要复制到新的数组。

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, 否则会产生数组越界的问题
            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
上一篇 下一篇

猜你喜欢

热点阅读