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]
這一篇跟前一篇多了一個條件,就是允許兩個重複的存在。
中間存在一個小小的坑,自己沒考慮到,就是如果相等且之前未重複過的話,那麼也是需要移位的。
比如[1,1,1,1,3,3]。A[4]一開始移到A[2]位置上,這個時候A[5]也是需要移到A[3]的。
上代碼:
public class Remove_Duplicates_from_Sorted_Array_II {
public class Solution {
public int removeDuplicates(int[] A) {
int lengthA = A.length;
if (lengthA == 0)
return 0;
int now = A[0];
int start = 0;
boolean same = false;
for (int indexA = 1; indexA < A.length; ++indexA) {
if (now == A[indexA] && same) {// 相等且重複過。
lengthA -= 1;
// same=false;
// start=indexA;
} else {
if (now == A[indexA]) {// 相等且未重複過
same = true;
A[start + 1] = A[indexA];// 相等且未重複過的話,有時候也是需要移動的!
start++;
} else if (start != indexA + 1) {// 不相等
A[start + 1] = A[indexA];
now = A[indexA];
start++;// 空閒位置右移
same = false;
}
// start = indexA;
}
}
return lengthA;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}