题目
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.
解题之法
class Solution {
public:
int removeDuplicates(vector<int>& A) {
int n = A.size();
if (n <= 1) return n;
int pre = 0, cur = 0;
while (cur < n) {
if (A[cur] == A[pre]) ++cur;
else A[++pre] = A[cur++];
}
return pre + 1;
}
};
分析
这道题要我们从有序数组中去除重复项,我们使用快慢指针来记录遍历的坐标,最开始时两个指针都指向第一个数字,如果两个指针指的数字相同,则快指针向前走一步,如果不同,则两个指针都向前走一步,这样当快指针走完整个数组后,慢指针当前的坐标加1就是数组中不同数组的个数,