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]
.
思考:双指针,A[i]与A[cur]前两个值比较。
class Solution { public: int removeDuplicates(int A[], int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(n==0) return 0; if(n==1) return 1; int cur=2; for(int i=cur;i<n;i++) { if(A[i]!=A[cur-2]||A[i]!=A[cur-1]) { A[cur]=A[i]; cur++; } } return cur; } };