题目:
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.
分析:
本题需要在有序数组中去重
采用双指针的方式访问vector,定义指针A,B,指针A负责访问整个数组,指针B用于修改vector,指针B保证总是指向一个之前从未出现过的元素。
逻辑是这样的:
- A、B一开始指向同一个元素;
- 移动规则,若A,B指向相同元素时,A向前移动一个;若A,B指向的元素不同,A,B同时指向下一个元素,并将B指向的元素赋值给A指向的元素(此时的A是已经移动过的);
- 当A遍历完整个数组后循环终止,B指向的数组索引+1即为非重复元素个数。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int pre = 0, cur = 0, n = nums.size();
while (cur < n) {
if (nums[pre] == nums[cur]) ++cur;
else nums[++pre] = nums[cur++];
}
return pre + 1;
}
};