【C++】去除排序数组中重复的元素

来源:互联网 发布:流星网络电视下载安装 编辑:程序博客网 时间:2024/06/13 03:21

题目: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 in place with constant memory.
将排序数组中重复的元素去除,并返回处理后数组的长度。
注意:需要将数组中的元素去除掉。
很暴力的算法,由于是排序后的,所以可以逐个比较,遇到前后相等的就去除后一个,遇到不相等的就sum+1;
代码如下:

int removeDuplicates(vector<int>& nums) {    int len=nums.size();    if(len<2)        return len;    int sum=1;    auto i=nums.begin();    auto j=i+1;    while(j!=nums.end()){        if(*i==*j){            j=nums.erase(j);            continue;        }        else{            sum++;            ++i;            ++j;        }    }    return sum;}

说明,对vector中的数据进行去除的时候,最好是用C++的迭代器,这样不容易出错。

vector<int>::iterator it;

这样写比较繁琐,也可以使用auto定义:

auto i=nums.begin();

最后用函数erase(i)删除数据的时候会迭代器i失效,但是会返回删除后数据的迭代器,所以正确的姿势应该是这样的:

j=nums.erase(j);