Leetcode 4. Remove duplicate elements from an ordered array remove duplicates from Sorted array

Source: Internet
Author: User

Issue: Remove duplicates from Sorted Array II Difficulty: Medium

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

Two ways of thinking:
(1) Two reference pointers, step back, and when the 3rd is equal to the first 2, skip
(2) A reference pointer, which is compared with 3rd and 1th, when equal, skips; unequal assignment
It is obvious that (1) is easy to think (intuitive), but (2) is more efficient and more scalable (if the requirements are up to 3 times, only the comparison of A[i] and a[index-3]).
Therefore, in the conception should pay attention to the conversion to the equivalence problem, when ordered, compare and the first n is equal, only need to compare the current and the first (i-n) equality.

 class solution { Public://Compare 1 times, assign value 1 times        intRemoveDuplicates (intA[],intN) {if(N <=2)returnNint Index=2; for(inti =2; I < n; i++) {if(A[i] = = a[Index-2])Continue; a[Index+ +] = A[i]; }return Index; }//Compare 2 times, assign value 2 times        intRemoveDuplicates2 (intA[],intN) {if(N <=2)returnNintj =0;intK = j+1; A[J] = a[0]; A[k] = a[1]; for(inti =2; I < n; i++) {if(A[i] = = A[k] && a[j] = = A[k])Continue;                A[++J] = a[k];            A[++K] = A[i]; }returnK +1; }    };};

Leetcode 4. Remove duplicate elements from an ordered array remove duplicates from Sorted 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.