leetcode 26 Remove Duplicates from Sorted Array

题目:

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

分析:

本题需要在有序数组中去重

采用双指针的方式访问vector,定义指针A,B,指针A负责访问整个数组,指针B用于修改vector,指针B保证总是指向一个之前从未出现过的元素。

逻辑是这样的:

  1. A、B一开始指向同一个元素;
  2. 移动规则,若A,B指向相同元素时,A向前移动一个;若A,B指向的元素不同,A,B同时指向下一个元素,并将B指向的元素赋值给A指向的元素(此时的A是已经移动过的);
  3. 当A遍历完整个数组后循环终止,B指向的数组索引+1即为非重复元素个数。
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0;
        int pre = 0, cur = 0, n = nums.size();
        while (cur < n) {
            if (nums[pre] == nums[cur]) ++cur;
            else nums[++pre] = nums[cur++];
        }
        return pre + 1;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiang_Tree

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值