LeetCode Remove Duplicates from Sorted Array, leetcodeduplicates

Source: Internet
Author: User

LeetCode Remove Duplicates from Sorted Array, leetcodeduplicates

Remove Duplicates from Sorted Array Total Accepted: 52196 Total Submissions: 165553 My Submissions Question Solution
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

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

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

Delete duplicate elements in an ordered array

Code 1:

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n==0)return 0;        int index=0;        for(int i=1;i<n;++i)        {            if(A[i]!=A[i-1])                A[++index]=A[i];        }        return index+1;    }};

161/161 test cases passed.
Status: Accepted
Runtime: 37 MS

Code 2 (network retrieval ):

// LeetCode, Remove Duplicates from Sorted Array // use STL, time complexity O (n), space complexity O (1) class Solution {public: int removeDuplicates (int A [], int n) {return distance (A, unique (A, A + n ));}}

161/161 test cases passed.
Status: Accepted
Runtime: 34 MS
In STL, the unique function is a deduplicated function. The unique function is used to remove adjacent duplicate elements (only one record is retained). In fact, it does not actually Delete duplicate elements, is to move the repeated elements to the back, and then save them to the original array, and then return the address of the last element after deduplication, because unique removes adjacent repeated elements, therefore, we usually sort the order before using it.
Distance returns the distance between two iterators.

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.