题目难度:Easy
分类:数组
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 by modifying the input array in-place with O(1) extra memory.
Example:
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 new length.
给定一个有序数组,你需要原地删除其中的重复内容,使每个元素只出现一次,并返回新的长度。
不要另外定义一个数组,您必须通过用 O(1) 额外内存原地修改输入的数组来做到这一点。
两个指针(Two Pointers)
使用两个索引(i,j)比对,如果nums[i] == nums[j],那么索引i+1的位置不应该填入j指向的值,这时j++;如果nums[i] != nums[j],那么索引i+1的位置应该填入j指向的值,这时i++,j++。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.empty())
return 0;
int i=0;
for(int j=1;j<nums.size();j++){
if(nums[i] != nums[j]){
i++;
nums[i]=nums[j];
}
}
return i+1;
}
};