原题: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],
这里还有更精简伶俐的写法:判断当前快指针所指元素是否与慢指针之前的那个元素相同,如果不相同那么重复次数一定小于3,即可满足条件。
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].
在元素递增的数组中,删除必要元素,使得单个元素的重复次数<=2。
首先可以想到的是用双指针,然后对元素重复次数计数,可以在O(N)时间内完成处理。
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(A==NULL || n<=0)
return 0;
int slow = 0, fast = 0;
int times = 1;
while(++fast<n){
if(A[fast]==A[fast-1]){
if(++times<=2)//判断重复次数是否小于等于2
A[++slow] = A[fast];
}else{
times = 1;//遇到新元素则计数置一
A[++slow] = A[fast];
}
}
return slow+1;
}
};
这里还有更精简伶俐的写法:判断当前快指针所指元素是否与慢指针之前的那个元素相同,如果不相同那么重复次数一定小于3,即可满足条件。
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(A==NULL || n<=2)
return n;
int slow = 1, fast = 1;
while(++fast<n){
if(A[fast]!=A[slow-1])
A[++slow] = A[fast];
}
return slow+1;
}
};
参考:https://oj.leetcode.com/discuss/2754/is-it-possible-to-solve-this-question-in-place