题目
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.
分析
从已排序数组中去除重复数字,但最多可以重复两次。利用上一题的思路:http://www.jianshu.com/p/2ea74e4e2f4c
就是需要判断两次,先判断和前个是否相同,之后判断再前面一个是否相同。
int removeDuplicates(int* nums, int numsSize) {
int length=1;
if(numsSize==0||numsSize==1)return numsSize;
if(nums[0]==nums[1])length=2;
for(int i=length;i<numsSize;i++)
{
if(nums[i]!=nums[length-1]||(nums[i]==nums[length-1]&&nums[i]!=nums[length-2]))
{
nums[length]=nums[i];
length++;
}
}
if(numsSize==0)return 0;
else return length;
}