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) {
if(A == null || A.length==0) return 0;
int len = A.length;
int i=0, k=0;
while(i<len){
int t = A[i++];
A[k++] = t;
if(i<len && A[i] == t){
A[k++] = t;
while(++i <len && A[i]==t);
}
}
return k;
}
}
更通用的版本:
public class Solution {
public int removeDuplicates(int[] A) {
if(A == null || A.length==0) return 0;
int len = A.length;
int i=0, k=0;
while(i<len){
int t = A[i];
int count = 0;
while(i<len && A[i] == t){
count++;
i++;
if(count <= 2)
A[k++] = t;
}
}
return k;
}
}