问题描述:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
示例:
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 j = 0;
int s = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == nums[s])
{
if (i - s < 2)
{
nums[j++] = nums[i];
}
}
else
{
s = i;
nums[j++] = nums[i];
}
}
return j;
}
};