question:
//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].
answer:
public class removeDuplicateTwo {
public static int removeDuplicateTwo(int[] array) {
if (array.length == 0) return 0;
int j =0;
int count =0;
for(int i = 1;i<array.length;i++){
if(array[j]==array[i]){
count++;
if (count<2){
j++;
array[j]=array[i];
}
}else {
j++;
array[j]=array[i];
count = 0;
}
}
return j+1;
}
public static void main(String[] args){
int[] array1={1,1,1};
int length =removeDuplicateTwo(array1);
for (int i=0;i<length;i++){
System.out.println(array1[i]);
}
System.out.println("this array length is "+length);
}
}
网友评论