题目
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
解答
这题又是一遍AC。。。只能说LeetCode上水题有点多,这居然都是Medium难度。。。
拿一个变量计数一下重复次数就可以了,每次遇到新的数就将这个变量赋值为1,如果这个变量达到2且遇到和之前重复的数,就移除。
下面是AC的代码:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0){
return 0;
}
int last = nums[0];
int count = 1;
int dup = 1;
for(vector<int>::iterator iter = nums.begin() + 1; iter != nums.end(); iter++){
if(*iter == last){
if(dup < 2){
dup++;
count++;
}
else{
nums.erase(iter);
iter--;
}
}
else{
dup = 1;
count++;
last = *iter;
}
}
return count;
}
};
118