题目:
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]
.
思路:双指针,设置一个flag,可以重复一次。
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (n <= 0) return n;
int runner = 0;
bool allow_dup = true;
for (int i = 1; i < n; ++i) {
if (A[i] == A[runner]) {
if (allow_dup) {
A[++runner] = A[i];
allow_dup = false;
}
} else {
allow_dup = true;
A[++runner] = A[i];
}
}
return runner + 1;
}
};
总结:复杂度为O(n).