【LeetCode】009 Move Zeroes 移零

本文介绍了一种有效的算法,用于将数组中的所有零元素移动到数组的末尾,同时保持非零元素的相对顺序不变。提供了两种实现方法,一种是通过删除和添加零元素的方式,另一种则是遍历并覆盖非零元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

给定一个数组,将数组中所有的“0”移到数组的末尾,保持数组中其他数字相对位置不变。

【解析】

思路一:

字面意思,对数组进行一次遍历,删除元素0,在数组末尾添加0。

程序如下:

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        i = 0
        while n:
            if nums[i] == 0:
                nums.append(0)
                del nums[i]
                i -= 1
            i += 1
            n -= 1
运用Python后,感觉粗暴的算法也能实现了!

思路二:

遍历一遍数组,如果该元素为零则不进行操作,如果该元素不为零则从数组的第一个元素开始进行覆盖,并且计数,最后将检索到的0添加到数组最后。

C++程序如下:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int j = 0;
        // move all the nonzero elements advance
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != 0) {
                nums[j++] = nums[i];
            }
        }
        for (;j < nums.size(); j++) {
            nums[j] = 0;
        }
    }
};

【关于bug】

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        for i in range(len(nums)):
            if nums[i] == 0:
                nums.append(0)
                del nums[i]
该程序出现的问题是删除了nums[i]以后,nums[i:]都会向前移动,因此标号i的位置会改变。因此在完成删除动作以后,应当加上语句使得i指向需要检索的下一个元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值