Remove Duplicates from Sorted Array II
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.
int removeDuplicates(int* nums, int numsSize) {
int i,j;
int k=0;
int flag=0;
for(i=0;i<numsSize;)
{
nums[k++]=nums[i];
flag=0;
for(j=i+1;j<numsSize;)
{
if(nums[j]==nums[i])
{
if(flag!=0) j++;
else
{ nums[k++]=nums[i];
flag++;
j++;
}
}
else break;
}
i=j;
}
return k;
}
增加标志,记录次数即可。