leetcode 刷题笔记 08-28 (双指针)

283. Move Zeroes

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

Note that you must do this in-place without making a copy of the array.

Example 1:

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

Example 2:

Input: nums = [0]
Output: [0]

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

Follow up: Could you minimize the total number of operations done?

这个题目偏简单(委婉的说法,实则简单到过分),本来不想发的,但考虑到自己双指针用的不太熟练,还是发个文章记录一下。

由于自己双指针用的不多,首先考虑的是一次遍历,个人觉得我这个方法其实不考虑使用双指针的话,还是该题比较不错的一个算法,时间复杂度为o(n),空间复杂度为o(1)。

考虑到往后放的元素都是0,我们可以在第一次遍历时,就把每个元素放在他该放的位置上,然后在后面进行补0,代码如下:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int count = 0;
        for(int i = 0;i < nums.size();i++)
        {
            if(nums[i] == 0)
            count++;
            else
            nums[i - count] = nums[i];
        }
        for(int i = nums.size() - count;i < nums.size();i++)
        {
            nums[i] = 0;
        }
    }
};

接下来是双指针的方法,其实上面的方法和双指针有着异曲同工之妙,如第10行的代码中的i-count和i就可以看作两个指针变量。下面给出双指针的代码:

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++;
            }
        }
        for(int i = j;i < nums.size();i++)
        {
            nums[i] = 0;
        }
    }
};

我认为这两种方法是基本相似的,只要找准了每个元素移动后的位置,双指针的优势在于元素移动先后的始末位置都很清晰,如该题,移动前的位置是i,移动后的位置是j,比第一种方法要清晰许多。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值