Leetcode每日一题2020.11.19第283题:移动零

题目描述

在这里插入图片描述
在这里插入图片描述

示例

在这里插入图片描述

思路、算法及代码实现

要把0移动到数组的末尾,还不能改变非0数字的相对位置,而且必须在原数组上进行操作。基于这些要求,我们可以想到遍历数组,碰到零的时候,通过零和零后面的非零元素调换位置,把零逐渐后移。将数组的两个位置的元素交换位置这个需求,可以用双指针来实现。左指针留在零上,右指针留在零后面的非零元素上。

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_51210480/article/details/111995722