LeetCode-Easy-Remove Duplicates from Sorted Array

###原题目
```cpp
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
In the any modification to the nums // your function Would BE Known by The Caller.
// The length returned by the using your function, IT Prints The First len Elements.
For (int I = 0; I <len; I ++) {
    Print (the nums [I]);
}
`` `
### of his first solution
stupid, so only thought of using erase operation to remove it, but also if used for loop and condition judgment, and in this case also being to change the container iterators issues fail to be updated, but their approach is too slow 163ms.
### excellent solution online
I did not think c ++ algorithm container has a unique, can be repeated on the back, then is deleted by erase, their foundation is not solid, need more training.
The following are comments hit my code, and not someone else's, really looked at his writing is Gesha ah.
```cpp
#include<iostream>
#include<vector>
using std::vector;
//class Solution {
//public:
// int removeDuplicates(vector<int>& nums) {
//   for (auto beg = nums.begin(); beg != nums.end(); beg++) {
//
//   if(beg!=nums.begin()&&*beg==*(beg-1))
//   {
//    beg=nums.erase(beg-1);//更新迭代器(重点)
//   }
//  }
//  return nums.size();
// }
//};
#include<algorithm>
class Solution {
public:
 int removeDuplicates(vector<int>& nums) {
  nums.erase(std::unique(nums.begin(), nums.end()), nums.end());
  return nums.size();
 }
 
};
int main() {
 Solution a;
 vector<int> test{ 1,1,2,2};
 std::cout << a.removeDuplicates(test)<<std::endl;
 for (auto a : test) {
  std::cout << a;
 }
}
```
### own ideas
really need to practice more, this line of code can solve things, can not be very complicated to think about, should think that comes with the operating, make good use of the various functions c ++ 11.

Guess you like

Origin www.cnblogs.com/Yekko/p/12130258.html