题目:
继续思考题目"Remove Duplicates":
如果数组中元素最多允许重复两次呢?
例如:
给出有序数组 A =[1,1,1,2,2,3],
你给出的函数应该返回length =5, A 变为[1,1,2,2,3].
package com.company;
public class TestNo7 {
public static void main(String[] args) {
TestNo7 t = new TestNo7();
int[] A1 = {1,1,2,2,2,3,4};
int[] A2 = {1,2,4,0,0,0};
System.out.println(t.removeDuplicates(A1));
System.out.println(t.removeDuplicates(A2));
}
public int removeDuplicates(int[] A) {
if(A == null){
return 0;
}else if(A.length <= 2){
return A.length;
}
int index = 1; //从1(也就是第二个数开始计数)
boolean canFill = true;
for(int i =1; i<A.length; i++){
if(A[i-1] == A[i]){
if(canFill){
A[index++] = A[i];
canFill = false;
}
}
else{
A[index++] = A[i];
canFill = true;
}
}
return index;
}
}