[Leetcode] Remove duplicates from Sorted Array II to remove duplicates in an ordered 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] .

This question is the continuation of the remove duplicates from the Sorted array in the ordered arrays, where the maximum number of repetitions allowed is two, then we need to record a variable count to allow a few repetitions, count initialized to 1, If there is a repetition, count decrements by 1, then the next occurrence repeats, the quick pointer is further, if this is not a duplicate, then count recovers 1, because the entire array is ordered, so once there are no duplicates, it must be larger than this number, and there will be no duplicates after this number. Clear up the above ideas, the code is very good to write:

classSolution { Public:    intRemoveDuplicates (intA[],intN) {if(N <=2)returnN; intPre =0, cur =1, Count =1;  while(Cur <N) {if(A[pre] = = A[cur] && count = =0) ++cur; Else {                if(A[pre] = = A[cur])--count; ElseCount =1; a[++pre] = a[cur++]; }        }        returnPre +1; }};

[Leetcode] Remove duplicates from Sorted Array II to remove duplicates in an ordered 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.