題目:
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].
思路
兩個指針,i用於遍歷A數組,index指向B數組中下一個可能的合法位置,初始設置爲index=2。
比較A[i]和B[index-2],若相等,說明i指向的元素不合法,此時不應該把A[i]加入到B中,i++;
若不想等,說明i指向的元素合法,應該設置B[index] = A[i],index++,指向下一個可能合法的位置。
java代碼
public int removeDuplicates2(int A[]) {
int n = A.length;
int[] B = new int[n];/
if (n < 3) // 最多含有2個元素,一定滿足題意
return n;
B[0] = A[0];
B[1] = A[1];
int index = 2; // 可能不合法的位置
for (int i = 2; i < n; i++) {
if (A[i] != B[index - 2])
B[index++] = A[i];
}
for(int i=0;i<n;i++)
A[i] = B[i];
return index;
}