1.题目描述
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.
2.解题思路
嗯,两个指针,扫一遍数组,O(n)
大概思路就是,前面的指针指向不出现不超过两次的,后面的指针指向出现超过两次的。
3.实现代码
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<=1){
return nums.size();
}
int i=0,j=1;
while(j<nums.size()){
if(nums[i]==nums[j]&&(i-1!=-1&&nums[i-1]==nums[j]))
++j;
else{
++i;
nums[i]=nums[j];
++j;
}
}
return i+1;
}
};