Remove Duplicates from Sorted Array II
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].
Code:
class Solution { public: int removeDuplicates(int A[], int n) { if(n<3) return n; int i=0; bool detect=false; for(int j=1;j<n;j++){ if(A[j]!=A[i]||detect==false){ if(A[j]!=A[i]) detect=false; else detect=true; A[++i]=A[j]; } } return i+1; } };