Delete duplicates in a sorted array

Source: Internet
Author: User

Given a sorted array, you need to delete the repeating elements in place so that each element appears only once, returning the new length of the array after removal.

Instead of using extra array space, you must modify the input array in place and complete it with O (1) Extra space.

My implementation: (Very low efficiency, 276ms)

classSolution { Public:    intRemoveDuplicates (vector<int>&nums) {        intRET =nums.size ();  for(inti =0; i< ret-1;) {            if(nums.at (i)! = nums.at (i+1))            {                ++i; Continue; }            Else            {                 for(intj = i; J < ret-1; ++j) {nums.at (j)= nums.at (j+1); } ret--; }                    }        returnret; }};

The Great God realizes: (16ms)

1 class Solution {2public:3     int removeduplicates (vector<int>& nums) {4         nums.erase (Std::unique (Nums.begin (), Mums.end ()), Nums.end ()); 5          return noms.size (); 6     }7 }    

Std::unique,

Eliminate other identical elements in a continuous group except for the first element;

The relative positions of the removed elements are not changed;

Return to the new Past-the-end;

Http://en.cppreference.com/w/cpp/algorithm/unique

A version of the reference Std::unique is implemented: (28MS)

classSolution { Public:    intRemoveDuplicates (vector<int>&nums) {        intRET =1; Vector<int>::iterator Beginiter =Nums.begin (); Vector<int>::iterator Enditer =Nums.end (); if(Beginiter = =enditer)return 0; Vector<int>::iterator Resultiter =Beginiter;  while(++beginiter! =enditer) {            if((*beginiter! = *resultiter)) {                  ++Resultiter; *resultiter = Std::move (*beginiter); ++ret; }        }        ++Resultiter; returnret; }};

Delete duplicates in a 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.