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].
Test instructions: You can keep a repeating element.
Idea: The first is a similar idea to the remove duplicates from sorted array. Compare a =[1,1,1,2,2,3] For example, the process of comparison is as follows
Here you can change the line 6th, line 10th 2 to 3, then the most repeated number appears three times, the code is:
1 classSolution2 {3 Public:4 intRemoveDuplicates (intA[],intN)5 {6 if(n<=2)returnN;7 intlo=2;8 for(intI=2; i<n;++i)9 {Ten if(A[i]!=a[lo-2]) Onea[lo++]=A[i]; A } - returnindex; - } the};
Method Two: Use the counter, when the two unequal counter reset, will a[i] assigned to the next bit of a[lo], equal but count not more than 2, will a[i] assigned to A[lo] the next bit, the rest, only counter + +, so you can successfully will be unequal after the case, the appearance of the second and A[i] When the case is equal, it is also assigned to the preceding element.
1 classSolution {2 Public:3 intRemoveDuplicates (intA[],intN)4 {5 intlo=0;6 intCount=0;7 if(n<3)returnN;8 9 for(intI=1; i<n;i++)Ten { One if(a[lo]==A[i]) A { -count++; - if(count<2) thea[++lo]=A[i]; - } - Else - { +a[++lo]=A[i]; -Count=0; + } A } at returnlo+1; - } -};
[Leetcode] Remove duplicates from sorted array II remove duplicate elements from a sorted array