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.
题意:从26题衍生过来,26题为去除重复,此题要求重复的个数最多为2个,返回数组的length。
思路:从重复的第二个开始删除,即引入一个flag变量即可。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
vector<int>::iterator it = nums.begin();
vector<int>::iterator it2;
while (it != nums.end()){
it2 = it;
it++;
bool flag = false;
while (it != nums.end() && *it == *it2){
if (flag){
it = nums.erase(it);
}
else{
flag = true;
it++;
}
}
}
return nums.size();
}
};
int main()
{
Solution s;
vector<int> nums(3,1);
nums.push_back(2);
nums.push_back(2);
nums.push_back(3);
int a = s.removeDuplicates(nums);
cout << a << endl;
return 0;
}