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]
.
class Solution {
public:
int removeDuplicates(int a[], int n) {
if(n==0) return 0;
int idx = 0, count = 0 , i = 0;
for ( i = 0; i < n ; i++) {
if (i >0 && a[i] ==a[i-1]) {
count++;
if(count >= 3){
continue;
}
}
else {
count = 1;
}
a[idx++] = a[i];
}
return idx;
}
};