0
点赞
收藏
分享

微信扫一扫

双指针——移动数组里的零

双指针——移动数组里的零

力扣283题
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:

输入: nums = [0]
输出: [0]


思路

输入数组有两个情况:

  1. 没有零
  2. 有零
    - 直接遇到零和遇到多个零
    - 先遇到非零
    直接代码走起
#include <vector>
using namespace std;
class Solution283 {
public:
    void moveZeroes(vector<int>& nums) {
    	//数组和迭代器一定要先辩空
        if (nums.empty()) { return; }
        int fastIndex = 0;
        int slowIndex = 0;
        //有可能第一位不是0或者没有0
        for (; nums[slowIndex] != 0 ; slowIndex++) {
            if (slowIndex == nums.size() - 1) return;
        }
        fastIndex = slowIndex;
        for (; slowIndex < nums.size(); slowIndex++) {
        	//遇到连续0直接将快指针放到0后
            for (; nums[fastIndex] == 0; fastIndex++) {
                if (fastIndex == nums.size()-1) return;
            }
            //这其实是一个虚假的交换
            if (nums[slowIndex] == 0) {
                nums[slowIndex] = nums[fastIndex];
                nums[fastIndex] = 0;
            }
        }
    }
};

以上是我第一个想法写法,让我们看看大神们的写法:
第一个是代码随想录的写法(我的刷题顺序是这个介绍的):他还有java版本我(差不多)
其讲解链接
他的方法是将0看作是要移除的元素

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
            if (nums[fastIndex] != 0) {
                nums[slowIndex++] = nums[fastIndex];
            }
        }
        // 将slowIndex之后的冗余元素赋值为0
        for (int i = slowIndex; i < nums.size(); i++) {
            nums[i] = 0;
        }
    }
};

官方的方法:
方法链接
使用了交换函数swap(),

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size(), left = 0, right = 0;
        while (right < n) {
            if (nums[right]) {
                swap(nums[left], nums[right]);
                left++;
            }
            right++;
        }
    }
};
举报

相关推荐

0 条评论