[LeetCode]283. Move Zeroes 解题报告(C++)

[LeetCode]283. Move Zeroes 解题报告(C++)

题目描述

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.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

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

题目大意

  • 给定一个数组. 将所有的 0 移动到后面
  • 要求不能改变非零数的相对应的位置关系!!!
  • 而且不能使用额外空间.

解题思路

方法1:

  • 不满足题目要求. 暴力解法.
  • 因为不能改变相对位置. 使用 queue 将所有非零的入队.再出队.
  • 最后补上0.
代码实现:
/*
    我的解法:不满足要求.使用了额外的空间
*/
void moveZeroes1(vector<int>& nums) {
    queue<int> q1;
    int num = 0;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i]!= 0) {
            q1.push(nums[i]);
        }
        else {
            num++;
        }
    }
    int i = 0;
    while (q1.size() )
    {
        nums[i] = q1.front();
        q1.pop();
        i++;
    }
    while (num) {
        nums[i] = 0;
        i++;
        num--;
    }
}

方法2:

  • 快慢指针
  • 快指针找到非零的元素与前面的指针交换位置.
  • 然后慢指针也自增
代码实现:
void moveZeroes2(vector<int>& nums) {
    for (int i=0,j=0;j<nums.size();j++)
    {
        if (nums[j]) {
            swap(nums[i], nums[j]);
            i++;
        }
    }
}

小结

  • 快慢指针 的方法非常优秀! 要记下来!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值