新手村:数组Array leetcode 283

Posted on 2022-05-21 10:47  shirleyx  阅读(19)  评论(0)    收藏  举报
# 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
# 请注意 ,必须在不复制数组的情况下原地对数组进行操作。

# 示例 1:
# 输入: nums = [0,1,0,3,12]
# 输出: [1,3,12,0,0]

# 示例 2:
# 输入: nums = [0]
# 输出: [0]

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        # 思路:[0,1,0,3,12] -> [1,3,12,0,0]
        # 填满数组前面非零数字的位置,后面位置全置为0。
        index = 0
        # 遍历数组
        for num in nums:
            # 找到非0数字,填入数组
            if num != 0:
                nums[index] = num
                index += 1
        # 非零数字位置填完后,剩余补0
        for i in range(index, len(nums)):
            nums[i] = 0

 

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        # 双指针法
        left = right = 0
        while (right < len(nums)):
            if(nums[right] != 0):
                 nums[left], nums[right] = nums[right], nums[left]
                 left += 1
            right += 1

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3