題目
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就是數組中不同數組的個數,