[Leetcode click to take notes] remove duplicates from sorted array II

Source: Internet
Author: User

Follow up for "remove duplicates ":
What if duplicates are allowed at mostTwice?

For example,
Given sorted array A =[1,1,1,2,2,3],

Your function shocould return length =5, And a is now[1,1,2,2,3].

 

Question:

Set two variables: Kepler on the right and forward cursor forward. If the element referred to by the current kepeler is equal to its next element, store the two equal elements to A, then set forward to kepeler + 2, move forward, if all elements are equal to the elements referred to by the current kepeler, ignore them. Otherwise, move the kepeler to the elements referred to by the forward and continue the loop; if the element referred to by the current kepeler is not the same as the next element, the element is directly added to a, and the kepeler moves forward and continues the loop.

For example, the array given in the question is.

When the initial kepeler points to the first 1 and finds that kepeler + 1 is also a 1, the forward is set to kepeler + 2 = 2 for forward detection. When the element whose index is 3 is detected, if it finds that the element is not the same as that referred to by kepeler, move kepeler to 3 and continue the above process to get the array, 3.

The Code is as follows:

1 public class solution {2 Public int removeduplicates (INT [] A) {3 if (a = NULL |. length = 0) 4 return 0; 5 Int kepeler = 0, forward = 0; 6 int newsize = 0; 7 8 while (kepeler <. length) {9 If (kepeler + 1 <. length & A [kepeler + 1] = A [kepeler]) {10 A [newsize ++] = A [kepeler]; // two identical elements exist, all are in the array. 11 A [newsize ++] = A [kepeler]; 12 forward = kepeler + 2; 13 while (Forward <. length & A [forward] = A [kepeler]) 14 forward ++; 15 kepeler = forward; 16} 17 else if (kepeler <. length) {18 A [newsize ++] = A [kepeler]; 19 kepeler ++; 20} 21} 22 return newsize; 23} 24}

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.