Follow up for "Remove duplicates":
What if duplicates is allowed at the 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] .
Hide TagsArray of Pointers This is easy to judge, set two index, one is traversed, one is the last position to return, because it is sorted, so that the value of the index and the last position and the previous value is equal, equal to continue to traverse, not equal to update the index.
1#include <iostream>2 using namespacestd;3 4 classSolution {5 Public:6 intRemoveDuplicates (intA[],intN) {7 if(n<3)returnN;8 //cout<<n<<endl;9 intretidx=1, Curidx =2;Ten for(; curidx<n;curidx++){ One //cout<<retidx<< "" <<curidx<<endl; A if(a[retidx]==a[curidx]&&a[retidx-1]==A[curidx]) - Continue; -A[++RETIDX] =A[curidx]; the } - returnretidx+1; - } - }; + - intMain () + { A inta[]={}; at solution Sol; - intret = Sol.removeduplicates (A,sizeof(a)/sizeof(int)); - for(intI=0; i<ret;i++) -cout<<a[i]<<" "; -cout<<Endl; - return 0; in}View Code
[Leetcode] Remove duplicates from Sorted Array II