"Remove duplicates from Sorted Array II" cpp

Source: Internet
Author: User

title :

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] .

Code :

classSolution { Public:    intRemoveDuplicates (intA[],intN) {if(N <=2)returnN; intindex =2;  for(intI=2; i<n; i++)        {            if(a[index-2]!=A[i]) {A[index++] =A[i]; }        }        returnindex; }};

Tips:

1. Index always points to the next location to insert the element

2. Determine whether the current element and index-2 position elements are equal, if not equal, can be inserted to ensure that there are no consecutive three identical elements

3. Here are some techniques for mathematical induction:

A. As long as the 1th-3rd element is not all the same

B. And when you add elements to each step, the judgment is not the same.

You can get the conclusion until the end of the condition, there will be no three consecutive repeating elements in the adjusted array

"Remove duplicates from Sorted Array II" cpp

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.