[Leetcode] Remove duplicates from Sorted array to remove duplicates in ordered arrays

Source: Internet
Author: User

Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.

Do the allocate extra space for another array, and you must does this on place with constant memory.

For example,
Given input Array A = [1,1,2] ,

Your function should return length = 2 , and A is now [1,2] .

The problem is to remove duplicates from the ordered array, which is similar to the previous remove duplicates from Sorted list to remove duplicates in the ordered list, but simply because the values of the array can be accessed directly through the subscript, but not the list. So the problem of the idea is that we use a fast pointer to record the traverse of the coordinates, at the beginning of the two pointers point to the first number, if the two pointer refers to the same number, then the quick pointer forward one step, if different, then two pointers forward one step, so that when the fast pointer through the entire array, The current coordinates of the slow pointer plus 1 are the number of different arrays in the array, the code is as follows:

classSolution { Public:    intRemoveDuplicates (intA[],intN) {if(N <=1)returnN; intPre =0, cur =0;  while(Cur <N) {if(A[cur] = = A[pre]) + +cur; ElseA[++pre] = a[cur++]; }        returnPre +1; }};

[Leetcode] Remove duplicates from Sorted array to remove duplicates in ordered arrays

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.