leetcode_27. 移除元素(双指针法)

题目描述:(. - 力扣(LeetCode))

核心思想:数组元素的删除其实就是覆盖,暴力解法也好双指针也好。

//常规双指针
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int write = 0;
        int len = nums.size();
        for (int read = 0; read < len; read++) {//读指针,读取符合要求的数组元素
            if (nums[read] == val) continue;
            nums[write++] = nums[read];//写指针,跟着读指针的后脚,覆盖符合条件的元素
        }
        return write;//刚好是数组的长度
    }
};
//官网的优化双指针
//其实思路是一样的,符合条件的元素就读取,写下覆盖
//这种解法打乱了原本的元素排序
//可以避免 1 2 3 4 5 删除val = 1 重复赋值操作
//感觉还是上面的解法更好
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
       int left = 0;
       int right = nums.size();
       while (left < right) {
            if (nums[left] == val) {
                nums[left] = nums[right-1];
                right--;
            }
            else {
                left++;
            }
       }
       return left;
    }
};

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值