Given a sorted array, 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 in place with constant memory.
For example,
Given input array 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 new length.
运行时间 26ms
#include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n =nums.size();
if(n<=1){return n;}
int res=1;
for(int i=1;i<n;++i){
if(nums[i]!=nums[i-1]){
nums[res]=nums[i];
res++;
}
}
return res;
}
};
void main(){
vector<int> nums;
nums.push_back(1);
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
Solution So;
int len=So.removeDuplicates(nums);
cout<<len<<endl;
}