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 i=1, j=0;
int count = 0;
if(A.length < 3)
return A.length;
while(i < A.length){
if(A[i] == A[j]){
if(count == 0){
A[++j] = A[i];
}
count++;
}else{
A[++j] = A[i];
count = 0;
}
i++;
}
return j+1;
}
}