题目英文描述:
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.
题目中午描述:
给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
思路 :双指针,一快一慢,慢指针始终指向新数组的最后一个位置,快指针用于遍历慢指针后面的数值。因为题目给定了一个有序数组,因此,只要两指针所指的值不相等,快指针所指的值就一定比慢的大,因此将快指针所指的值移动到慢指针所指位置的下一个位置。最后,因为慢指针始终指向新数组的最后一个位置,所以长度为慢指针的值+1。
代码:
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;
}
};
PS:27题类似