一、问题描述
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.
二、思路
如果有相同的元素,删除并且计数减一。
注意:vector的函数erase在删除完元素会跳到下一个位置,所以我们必须手动跳回原来的位置,即--i;
三、代码
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if(len == 0) return 0;
for(int i = 0 ; i < nums.size() - 1; i++){
if(nums[i] == nums[i + 1]){
nums.erase(nums.begin() + i);
--i;
--len;
}
}
return len;
}
};