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.
Subscribe to see which companies asked this question
其实就是循环计数问题,每次比对及出现次数,由于已经排好序,很好做。
class Solution {
public:
int removeDuplicates(vector
vector
int now = 0;
for(int i = 0 ; i < nums.size();i++)
{
if(count.empty())
{
count.push_back(nums[i]);
now = 1;
}
else
{
if(nums[i]==count.back())
{
if(now == 2)
continue;
else
{
now++;
count.push_back(nums[i]);
}
}
else
{
count.push_back(nums[i]);
now=1;
}
}
}
nums.clear();
copy(count.begin(),count.end(),nums.begin());
return count.size();
}
};