Leetcode Remove duplicates from Sorted Array II

Source: Internet
Author: User

Title: Give a sorted array, remove duplicate elements in the array and allow up to two elements of the same, and finally return the processed array length, and the array is collated.

Algorithm idea: When the array length is less than 3 o'clock do not tidy up the array, directly return the length of the array; When the array length is greater than or equal to 3 o'clock, with the pre record of the precursor element, the flag tag repeats once, p records the end coordinates of the new array, and then scans the entire array, adjacent to two elements, if identical and flag= 0 The elements of the comparison are put into the new array, flag=1, and conversely, if the magnitude element is the same then continue, if not the same, put the comparison element into the new array flag=0.

The code is as follows:

Class Solution {public:     int removeduplicates (int a[], int n) {            int p;//record end of new array            int pre;//forward variable            int flag ;//Mark element repeats several times            if (n==0| | n==1| | n==2) {                return n;            }            else{                pre=a[0];                flag=0;                P=1;                for (int i=1;i<n;i++) {                     if (pre==a[i]&&!flag) {                         a[p++]=a[i];                          flag=1;                         }                    else{                         if (pre==a[i]) continue;                        else{                            Pre=a[i];                            A[p++]=a[i];                            flag=0                  ;                }}} return p;}}           ;


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.