1. 程式人生 > >LeetCode 26. Remove Duplicates from Sorted Array(刪除排序陣列中的重複項)

LeetCode 26. Remove Duplicates from Sorted Array(刪除排序陣列中的重複項)

題目描述:

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.

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4
respectively. It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

給定一個排序陣列,你需要在原地刪除重複出現的元素,使得每個元素只出現一次,返回移除後陣列的新長度。

不要使用額外的陣列空間,你必須在原地修改輸入陣列並在使用 O(1) 額外空間的條件下完成。

示例 1:

給定陣列 nums = [1,1,2], 

函式應該返回新的長度 2, 並且原陣列 nums 的前兩個元素被修改為 1, 2。 

你不需要考慮陣列中超出新長度後面的元素。

示例 2:

給定 nums = [0,0,1,1,1,2,2,3,3,4],

函式應該返回新的長度 5, 並且原陣列 nums 的前五個元素被修改為 0, 1, 2, 3, 4。

你不需要考慮陣列中超出新長度後面的元素。

說明:

為什麼返回數值是整數,但輸出的答案是陣列呢?

請注意,輸入陣列是以“引用”方式傳遞的,這意味著在函式裡修改輸入陣列對於呼叫者是可見的。

你可以想象內部操作如下:

// nums 是以“引用”方式傳遞的。也就是說,不對實參做任何拷貝
int len = removeDuplicates(nums);

// 在函式裡修改輸入陣列對於呼叫者是可見的。
// 根據你的函式返回的長度, 它會打印出陣列中該長度範圍內的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

解法一(My Solution):

題目給的是有序的陣列,目的是去重,那麼我們只要遍歷一遍陣列,判斷前後兩個連續位置的數字是否相同,只有兩者不同時才將 nums[i] 複製到 nums[nonRepeat++],思路很簡單,下面給出程式碼

public int removeDuplicates(int[] nums) {

    int nonRepeat = 0; // 指向新陣列中不重複元素的下標
    for (int i = 1 ; i < nums.length ; i ++) {
        if (nums[i] != nums[i-1])
            nums[++ nonRepeat] = nums[i];
    }
    return nonRepeat + 1;
}

解法二(Two Pointers):

陣列完成排序後,可以設定兩個指標 i 和 j,其中 i 是慢指標,j 是快指標。只要 nums[i] == nums[j],就增加 j 跳過重複項。

當 nums[i] != nums[j],則就要把 nums[j] 的值複製到 nums[i + 1] 。然後遞增 i,重複相同的過程,直到 j 到達陣列的末尾為止。

public int removeDuplicates(int[] nums) {
    int nonRepeat = 0;
    for (int j = 1 ; j < nums.length ; j ++) {
        if (nums[nonRepeat] != nums[j])
            nums[++nonRepeat] = nums[j];
    }
    return nonRepeat + 1;
}