Remove Duplicates from Sorted Array [LeetCode]

Remove Duplicates from Sorted Array


Analysis

周末下午日常刷题啦~ 下周末或者下下周一表妹就要来上海玩啦,所以下周末可能就没时间刷题了,但是寒假会有很多时间刷题哦~

Given a sorted array, 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.
这道题还是很简单啦,就是说给我一个数组,然后对这个数组进行去重,最后统计出去重之后的数组中的元素个数。这里需要注意的是,这个给我们的数组里面的元素已经按着从小到大的顺序排好了,然后题目的要求是空间复杂度为O(1),也就是说我们不能再开一个数组用来记录,因此我们直接用两个指针对数组进行扫描就行了。一个指针是pre,另一个是cur。pre表示前面一个元素,cur表示现在扫描到的元素。所以当pre所指的元素等于cur所指的元素,那么就说明出现重复元素,则让cur+1然后接着扫描下一个,否则说明相邻元素不是重复的,那就让pre+1,同时让cur+1,然后继续扫描。

implement

@Cherry Ye
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.empty())
            return 0;
        int pre = 0;
        int cur = 0;
        int n = nums.size();
        while(cur<n){
            if(nums[pre]==nums[cur])
                cur++;
            else{
                nums[++pre] = nums[cur];
                cur++;
            }
        }
        return pre+1;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值