[LeetCode]283. Move Zeroes(把0移到数组后面)

本文介绍了一种不使用额外数组空间,将数组中所有0元素移动到末尾同时保持非零元素相对顺序的方法,并提供了两种不同的C++实现方案。

283. Move Zeroes

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].

Note:

You must do this in-place without making a copy of the array.
Minimize the total number of operations.

题目大意:
给定一个数组,将所有的0移到数组后面并保持非0值顺序不变(不能占用额外的数组空间)

代码如下:

C++

#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int j = 0;
        for(int i=0; i<nums.size(); i++)
        {//将所有非零值移到前面
            if(nums[i] != 0)
            {
               nums[j] = nums[i];
               j += 1;
            }
        }
        for(; j<nums.size(); j++)//剩下元素的全部赋值为0
            nums[j] = 0;
    }
    void moveZeroes1(vector<int>& nums) {
        int j = 0;
        int num = nums.size();
        for(int i=0; i<num; i++)
        {
            if(nums[i] != 0)
            {
               nums[j] = nums[i];//非零值 移位
               if(i != j)
               {//将移动的元素之前的位置赋值0
                   nums[i] = 0;
               }
               j += 1;
            }
        }
    }
};
int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

注意:
1.刚开始还以为还得把非零值排序,后来才发现非零值保持原来前后顺序不变就行了
2.第二种方法用一个循环就把完成了,移动元素的同时将之前位置赋值0

### LeetCode 283 题目解析 LeetCode283 题名为 **Move Zeroes**,其目标是将数组中的所有零移动到数组的末尾,同时保持非零元素的相对顺序。以下是基于此问题的一种高效解决方案。 #### 方法描述 一种常见的解决方法是通过双指针技术实现。具体来说,定义两个指针 `i` 和 `j`,其中 `i` 负责遍历整个数组,而 `j` 则用于记录下一个非零元素应该放置的位置。当遇到非零元素时,将其交换至位置 `j` 并更新 `j` 的值。这种方法的时间复杂度为 O(n),空间复杂度为 O(1)。 下面是具体的代码实现: ```python class Solution: def moveZeroes(self, nums): """ Do not return anything, modify nums in-place instead. """ j = 0 # 记录下一个非零元素应放的位置 for i in range(len(nums)): if nums[i] != 0: # 如果当前元素不是零,则将其移到前面 nums[j], nums[i] = nums[i], nums[j] j += 1 # 更新非零元素的目标索引 ``` 上述代码的核心逻辑在于利用原地操作来减少额外的空间开销[^6]。 --- #### 测试用例验证 为了确保算法的有效性和鲁棒性,可以设计一些测试用例对其进行验证。例如: ```python # 初始化类实例 solution = Solution() # 测试用例 1 nums_1 = [0, 1, 0, 3, 12] solution.moveZeroes(nums_1) print(nums_1) # 输出应为 [1, 3, 12, 0, 0] # 测试用例 2 nums_2 = [0, 0, 1] solution.moveZeroes(nums_2) print(nums_2) # 输出应为 [1, 0, 0] ``` 以上测试用例展示了不同输入情况下的正确输出结果。 --- #### 性能分析 该算法仅需一次遍历即可完成任务,因此时间复杂度为 \(O(n)\),其中 \(n\)数组长度。由于不需要任何额外的数据结构存储中间状态,故空间复杂度为 \(O(1)\)[^7]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值