[leetcode] 283. Move Zeroes

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:
   1. You must do this in-place without making a copy of the array.
   2. Minimize the total number of operations.

题意:
            给定数组nums,写一个函数来移动所有的元素0到数组的末尾,同时保持非零元素在数组中的相对顺序。

注意:
   1. 你必须在本数组空间内完成,不能复制数组。
   2. 减少操作的总数。

方法一:
   思路:
            利用vector的erase()方法删除指定位置的元素,其中erase()方法的参数是位置的迭代器。
例如:vec.erase(vec.begin()+2);//删除第3个元素

void moveZeroes(vector<int>& nums) {
    int n=nums.size();
    for (int i=0;i<nums.size();i++)
    {
        if(nums[i]==0) {
            nums.erase(nums.begin()+i);//删除第i个为0的元素
            i=-1;//重置下次迭代的起始点从数组的首元素开始
        }
    }
    int m=nums.size();
    for (int i=0;i<(n-m);i++)
    {
        nums.push_back(0);//填充删掉的0元素在数组末尾
    }
}

方法二:
   思路:
            利用双指针,一前一后遍历nums数组,right在前,left在后。如果right所指元素非0且left为0则交换,left所指元素非零的时候向前移动,right所指元素不管是否是0都向前移动(因为当不为0时进行交换后变为0,为0直接移动)。代码如下:

void moveZeroes(vector<int>& nums) {
    int n = nums.size();
    int left = 0, right = 0;
    while (right < n){
        if (nums[right] != 0 && nums[left] == 0){
            swap(nums[left], nums[right]);
            left++;
        }
        if (nums[left] != 0)
            left++;
        right++;
    }
}

方法三:
   思路:
            和方法二类似,利用双指针,一前一后遍历nums数组,right在前,left在后。此代码利用一个巧妙的地方就是刚刚开始left==right,只要right所指元素不为0,left和right同时向前移动,如果right所指元素为0,则right向前移动,left记录为0元素的位置,当right所指元素不为0时直接覆盖left所指元素并且left向后移动,最后补全后面缺省的元素0。代码如下:

void moveZeroes(vector<int>& nums) {
    int n = nums.size();
    int left = 0, right = 0;
    while (right < n){
        if (nums[right]){
            nums[left] = nums[right];
            left++;
        }
        right++;
    }
    while (left < n)
        nums[left++] = 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值