Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
思路:依然是双指针遍历
代码:
int removeDuplicates(int A[], int n) {
if(n <= 2)
return n;
int res=1;
int i=0;
int j=1;
while(j < n)
{
if(A[i] == A[j])
{
if(j == i+1)
{
A[res++]=A[j];
}
++j;
}
else
{
A[res++]=A[j];
i=j;
++j;
}
}
return res;
}