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