Skip to content

LeetCode: 26-Remove Duplicates from Sorted Array 解題紀錄

Last Updated on 2021-02-07 by Clay


題目

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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.

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 a modification to the input array will be known to the caller as well.

Example:

Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: 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.

題目輸入一個由小到大排序的陣列,我們需要回傳『沒有重複元素陣列長度』,並將這些沒有重複的元素移動至該陣列的開頭。

當然你可以選擇刪除掉重複的元素,但驗證時只會依照你回傳的長度進行該陣列的檢測。比方說你回傳 1,那麼驗證機制只會檢測陣列開頭第 1 個元素。


解題思路

最開始我也以為只能『刪除重複元素』,但實際上執行過後才發現,跟『將不重複元素移動至陣列開頭』相比時間代價太高。

移動不重複元素至陣列開頭很簡單,畢竟這是個已經排序過後的陣列,我們只需要進行以下動作:

  • 紀錄要改動的陣列位置 index
  • 若當前元素跟前一個元素相比值不同,則代表這是出現的第一個元素
  • 陣列開頭的第一個元素一定是新的元素


C++ 程式碼

class Solution {
public:    
    int removeDuplicates(vector<int>& nums) {
        // Init
        int index = 0;
        
        // Walk
        for (int i=0; i<nums.size(); ++i) {
            if (i == 0 || nums[i] != nums[i-1]) {
                nums[index] = nums[i];
                ++index;
            }
        }

        return index;
    }
};


Python 程式碼

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        # Init
        index = 0
        
        # Walk
        for i in range(len(nums)):
            if (i == 0 or nums[i] != nums[i-1]):
                nums[index] = nums[i]
                index += 1
        
        return index
                



References

Leave a Reply