题目如下:
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].
分析如下:
用两个指针。第一个指针j去查看每个数组的第j位和第j+1位,如果这相邻的两位不同,则可以直接放入新生成的数组中,用i表示新生成的数组的下标。
如果j和j+1这相邻的两位相同,则一方面把这两个都放入新生成的数组中,另一方移动j直到j和当前放入的最新的元素不同位置。
因为新数组滤重了,所以长度不会大于原数组。所以可以在原数组基础上生成新的数组。这道题目的前集中有在原数组基础上生成新数组的解释。
我的代码:
//24ms
class Solution {
public:
int removeDuplicates(int A[], int n) {
int i = 0, j = 0; //j去查看原数组进行滤重,i放入滤重后的元素
while (i < n && j < n) {
if (j+1 < n && A[j] == A[j+1]){
A[i] = A[j];
A[i+1] = A[j];
i = i+2; //下一个待放入元素应该放在i
while (A[j] == A[i-1]) //已经放好的最后一个元素在i-1
++j;
} else {
A[i] = A[j];
++i;
++j;
}
}
return i;
}
};