问题描述:
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.
分析:这里需要加一个计数的变量。
代码如下:8ms
int removeDuplicates(int* nums, int numsSize) {
int res = 0;
int count = 1;
for(int i = 0;i<numsSize;i++){
while(i>0 && i<numsSize && nums[i] == nums[i-1] && ++count>2) i++;
if(i==numsSize)
break;
if(nums[i]!=nums[i-1])
count = 1;
nums[res++] = nums[i];
}
return res;
}