Remove Duplicates from Sorted Array II
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]
.
用两个指针,记录当前元素的上一个和上上个
每当发现相同时,count++,同时A[i-count]=A[i]
class Solution {
public:
int removeDuplicates(int A[], int n) { int p1=;
int p2=;
if(n<=) return n; int count=;
for(int i=;i<n;i++)
{
if(A[p1]==A[p2]&&A[p2]==A[i])
{
count++;
continue;
}
else
{
A[i-count]=A[i];
}
p1++;
p2++;
}
return n-count;
}
};