题目:
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.
解答:
很明显的用两个指针和计数来做,用一个指针表示现在正在进行计数的数字,另一个指针表示现在处理的位置
代码很明显如下
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int start = 0;
int end = 1;
int size = nums.size();
if(size <= 2)
return size;
int cnt = 1;
while(end < size)
{
if(nums[start] == nums[end])
{
if(cnt < 2)
{
nums[++start] = nums[end++];
}
else
{
end++;
}
cnt++;
}
else
{
nums[++start] = nums[end++];
cnt = 1;
}
}
return start + 1;
}
};