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]
.
public class Solution {
public int removeDuplicates(int[] A) {
int index = -1, length = A.length, mult = 0;
if(length > 0){
index = 0;
mult = 1;
int current = A[0];
for(int i = 1; i < length; ++i) {
if(current != A[i]){
A[++index] = A[i];
mult = 1;
current = A[i];
}
else{
if(mult < 2){
A[++index] = A[i];
++mult;
}
}
}
}
return index + 1;
}
}