算法養成記:刪除排序數組中的重複項

  • 2020 年 3 月 12 日
  • 筆記

LeetCode26

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]);

}

在實際測試里

執行用時分別是:0ms,0ms

內存消耗分別是:41.7MB,41.3MB

這題幾乎沒有難度,但是能夠寫得簡潔漂亮,就會有些困難了。