Leetcode 26. Remove duplicates from Sorted array

Source: Internet
Author: User

Remove Duplicates from Sorted Array


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  nums  = [1,1,2] ,

your function should return length = 2 , with the first elements of  nums  being 1  and 2  respectively. It doesn ' t matter what are you leave beyond the new length.

Main topic:

Delete a repeating element in an ordered series without applying for another space. Returns the length of the final array.

The code is as follows:

Class solution {public:    int removeduplicates (vector<int>&  nums)  {        if  (Nums.empty ()  | |  nums.size ()  == 1)              Return nums.size ();        int cur = nums[0];         int i = 0;         while (I != nums.size ()  - 1 )          {            if (Cur == nums[i+1])             {                 nums.erase (Nums.begin ()  + i +  1);        &Nbsp;    }            else             {                 cur = nums[i+1];                 i++;             }        }         return nums.size ();    }};

If you don't need to delete the element, just count the last number. You can use the following concise approach:

Reference from: Https://discuss.leetcode.com/topic/8907/share-my-clean-c-code

int count = 0;for (int i = 1; i < n; i++) {if (a[i] = = a[i-1]) count++;else a[i-count] = a[i];} return n-count;


Other ideas:

(using extra space, the subject does not apply) put the array elements in the map and then output the map size.


2016-08-11 14:33:57

This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1836874

Leetcode 26. 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.