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]
.
Code:
<span style="font-size:14px;">class Solution {
public:
int removeDuplicates(int A[], int n) {
if (n == 0 || n == 1 || n == 2) return n;
int index = 1;
bool duplicate = false;
for (int i = 1; i < n; i++) {
if (A[i] == A[i-1] && !duplicate) {
A[index++] = A[i];
duplicate = true;
} else if (A[i] != A[i-1]) {
A[index++] = A[i];
duplicate = false;
}
}
return index;
}
};</span>