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]
.
class Solution {
public:
int removeDuplicates(int A[], int n) {
int newlength = n;
for(int ii = n - 1; ii >= 0; ii --) {
int current = A[ii];
//Search to left
int count = 1;
while(ii - count >= 0 && A[ii - count] == current) {
count ++;
}
if(count > 2) {
newlength -= count - 2;
for(int jj = ii - count + 2; jj < newlength; jj ++) {
A[jj] = A[jj + count - 2];
}
ii -= count - 2;
}
}
return newlength;
}
};