Leetcode Remove duplicates from Sorted Array II

Source: Internet
Author: User

Title Address: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

Problem analysis: First need an array subscript used to traverse the array elements, while in the process of traversing the number of numbers greater than 2 to keep only 2, that is, you need to move the elements behind the array forward, that is, you need to maintain an array subscript, indicating the insertion position of the following elements In the traversal process, you need to save the currently found number, and the previously found number, as well as record the number of repeated occurrences, if a number is less than two repetitions are inserted directly in front of the array (where the insertion index points), insert the index plus 1, if more than two times, do not insert, the insertion index is unchanged Once a new element is found, the counter is set to 1.

Topic Answer:

 Public classSolution { Public intRemoveDuplicates (int[] A) {if(A = =NULL|| A.length = = 0){            return0; }                intCount = 1; intCurr = a[0]; intInsertindex = 1; intFoundindex = 1;  while(Foundindex <a.length) {            if(Count < 2) {A[insertindex++] =A[foundindex]; if(Curr = =A[foundindex]) {Count++; }Else{Count= 1; Curr=A[foundindex]; }            }Else {                if(Curr! =A[foundindex]) {A[insertindex++] =A[foundindex]; Curr=A[foundindex]; Count= 1; }} Foundindex++; }        returnInsertindex; }}

Leetcode Remove duplicates from Sorted Array II

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.