leetcode 26 -- Remove Duplicates from Sorted Array
Remove Duplicates from Sorted Array
题目:
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.
For example,
Given input array nums = [1,1,2],
题意:
给排序后的字符串去除反复的而且返回去重后的长度。要求不能使用辅助空间。
思路:
定义两个迭代器,相等则erase,不相等cnt++,注意迭代器删除后失效的情况。
代码:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0){
return 0;
}
if(nums.size() == 1){
return 1;
}
auto iter2 = nums.begin();
int cnt = 1;
for(auto iter = nums.begin()+1; iter != nums.end(); ){
if(*iter2 != *iter){
cnt++;
iter2 = iter;
++iter;
}else{
iter = nums.erase(iter);
}
}
return cnt;
}
};