1. 程式人生 > >[LeetCode] Remove Duplicates from Sorted Array 有序陣列中去除重複項

[LeetCode] Remove Duplicates from Sorted Array 有序陣列中去除重複項

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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2]

.

這道題要我們從有序陣列中去除重複項,和之前那道 Remove Duplicates from Sorted List 移除有序連結串列中的重複項 的題很類似,但是要簡單一些,因為畢竟陣列的值可以通過下標直接訪問,而連結串列不行。那麼這道題的解題思路是,我們使用快慢指標來記錄遍歷的座標,最開始時兩個指標都指向第一個數字,如果兩個指標指的數字相同,則快指標向前走一步,如果不同,則兩個指標都向前走一步,這樣當快指標走完整個陣列後,慢指標當前的座標加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; } };

我們也可以用for迴圈來寫,這裡的j就是上面解法中的pre,i就是cur,所以本質上都是一樣的,參見程式碼如下:

解法二:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0;
        int j = 0, n = nums.size();
        for (int i = 0; i < n; ++i) {
            if (nums[i] != nums[j]) nums[++j] = nums[i];
        }
        return j + 1;
    }
};

類似題目: