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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值