[Leetcode] Remove duplicates from sorted array II remove duplicate elements from a sorted array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.