LeetCode26. Remove Duplicates from Sorted Array

1.问题描述

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.

Example:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

2.思考过程

这是一个已经排序的数组,那么相同的元素必然摆放在一起,可以用一个变量pos记录当前数组保存的下标,再用一个临时变量cur记录当前的这一个数字,然后向后遍历,直到遇到下一个不同数字的时候,便将这个值放在pos上,并将pos加一,再将cur更新为下一个数。

值得注意的是最后一个数字不会保存下来,所以在循环结束后要对最后一位数字进行处理。而且测试代码中会有vector中没有数字的情况,要特判一下。代码如下

3.代码实现及其优化

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0) return 0;
        int cur = nums[0];
        int pos = 0;
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] != cur){
                nums[pos++] = cur;
                cur = nums[i];
            }
        }
        nums[pos++] = cur;
        return pos;
    }
};

然而vector中包括了unique这个操作,可以通过直接调用STL库来解决这一问题,代码如下

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        nums.erase(unique(nums.begin(), nums.end()), nums.end());
        return nums.size();
    }
};

unique(nums.begin(), nums.end())会返回排序后最后一个值的迭代器,通过erase,便能够删除后面的元素,从而保证nums.size()返回的是新的长度

4.问题拓展

对于删除数组重复元素问题一般有三类

1.有序数组,不能开辟额外空间

2.无序数组,不能开辟额外空间

3.无序数组,可以开辟额外空间

1.本题便是有序数组,不能开辟额外空间的情况,方法如上

2.对于无序数组,但又不能开辟额外空间的情况,要先对其进行排序,再按照第一类进行处理

3.对于无序数组,可以开辟额外空间的情况,可以通过建立hash表,通过访问hash表来确定该元素是否重复

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值