问题:Followup for "Remove Duplicates":What if duplicates are allowed at most twice?Forexample,Given sorted array nums = [1,1,1,2,2,3],Yourfunction 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.
紧接着上一题,每个元素最多允许出现两次。
思考:还是两个游标,i和j,如果数组长度本身小于3,直接输出无变化。如果长度大于3,从第三个开始,一次与它的前面第两个值比较,如果不同,赋值给j。j要从2开始。
代码:classSolution {
public:
int removeDuplicates(vector<int>& nums) {
int l=nums.size();
if(l < 3)
return l;
int j = 2;
for(int i = 2; i < l; i ++) {
if(nums[i] != nums[j-2])
nums[j ++] = nums[i];
}
return j;
}
};