问题:Remove Duplicates from Sorted Array II 难度:medium
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)两个参考指针,逐步后移,当第3个与前2个相等时,跳过
(2)一个参考指针,用第3个和第1个做比较,相等时,跳过;不等赋值
显然第(1)容易想到(直观),但是第(2)比较高效,而且扩展性比较强(如果要求最多出现3次,只需要比较A[i]和A[index-3])。
因此在构思时应该注意转换成等价问题,有序时,比较和前n个是否相等,只需要比较当前是否和第(i-n)个相等。
class Solution {
public:
//比较1次,赋值1次
int removeDuplicates(int A[], int n) {
if (n <= 2)
return n;
int index = 2;
for (int i = 2; i < n; i++) {
if (A[i] == A[index-2])
continue;
A[index++] = A[i];
}
return index;
}
//比较2次,赋值2次
int removeDuplicates2(int A[], int n) {
if (n <= 2)
return n;
int j = 0;
int k = j+1;
A[j] = A[0];
A[k] = A[1];
for (int i = 2; i < n; i++) {
if (A[i] == A[k] && A[j] == A[k])
continue;
A[++j] = A[k];
A[++k] = A[i];
}
return k+1;
}
};
};
时间: 2024-10-29 15:30:23