[Leetcode] Remove Duplicates from Sorted Array

Source: Internet
Author: User

Test instructions

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

Given an ordered array, the number of paired occurrences in the array is removed, guaranteeing that each number in the array appears only once, returning the final array length.

The point to note is not only to detect the length of the returned array, but also to check the contents of the returned array.

The idea is to set two subscript, a I traverse the entire array, an index record currently needs to compare the number, but also the length of the returned array, if encountered during the traversal of a[i] not equal to A[index], will a[i] inserted after the a[index], the implementation code is as follows:

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[index]) {A[++index] = A[i];    When A[i] is not equal to the value of the current index, A[i] is inserted after index}}return index + 1;    }

  

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