```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); // any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
```
###自己第一次的解法
比较笨,所以只想到了用erase操作来进行删除,而且还用了for循环以及if条件判断,而在这之中还遇到了改变容器迭代器失效需要更新的问题,而自己的方法是163ms实在太慢。
###网上优秀的解法
我没想到c++容器算法中有一个unique,可以将重复的放在后面,然后通过erase进行删除便是,自己的基础不扎实,需要多训练。
以下打了注释的是我的代码,然后没有的是别人的,看了一下真的自己的写的是个啥啊。 ```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;
} }
``` ###自己的想法
真的需要多加练习,这种一行代码就能解决的东西,不能再很复杂的去想,应该多想自带的操作,利用好c++11的各种功能。