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.length==0 )
return 0;
int count = 0;
List<Integer> list = new ArrayList<Integer>();
list.add(A[0]);
count++;
for( int i=1; i<A.length; i++ ){
if( A[i]==A[i-1] ){
count++;
if( count<=2 ){
list.add(A[i]);
}
}else{
count = 1;
list.add(A[i]);
}
}
for( int i=0; i<list.size(); i++ ){
A[i] = list.get(i);
}
return list.size();
}
}