【C++】去除排序数组中重复的元素
题目: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);
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了