iT邦幫忙

0

解LeetCode的學習筆記Day26_Remove Duplicates from Sorted Array

LFI 2025-10-17 20:38:50151 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第二十六天

第二十六題題目:Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

給定一個按照非遞減順序(由小到大)排序的整數陣列 nums,原地移除重複的元素,使得每個唯一元素只出現一次,同時,元素的相對順序必須保持不變,然後回傳移除重複後的唯一元素數量 k

程式碼

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i = 0 #指向最後一個不重複的元素位置
        for j in range(1, len(nums)):
            #當前元素與上一個不相同
            if nums[j] != nums[i]:
                i += 1
                nums[i] = nums[j]

        return i + 1

這題可以用set或dict.fromkeys()的方式去除重複元素,因為set和dictionary的key都有唯一(不重複)的特性,不過官方給出雙指針的解法,所以我們也用此解法來寫這題。ps:不然用集合或字典這題會太簡單w

執行過程

初始狀態

  • nums = [0,0,1,1,1,2,2,3,3,4]
j nums[j] i nums[i] 動作
1 0 0 0 相同 → 跳過
2 1 0 0 不同 → i+1 → nums[1] = 1 → nums = [0,1,1,1,1,2,2,3,3,4]
3 1 1 1 相同 → 跳過
4 1 1 1 相同 → 跳過
5 2 1 1 不同 → i+1 → nums[2] = 2 → nums = [0,1,2,1,1,2,2,3,3,4]
6 2 2 2 相同 → 跳過
7 3 2 2 不同 → i+1 → nums[3] = 3 → nums = [0,1,2,3,1,2,2,3,3,4]
8 3 3 3 相同 → 跳過
9 4 3 3 不同 → i+1 → nums[4] = 4 → nums = [0,1,2,3,4,2,2,3,3,4]

最後回傳i + 1也就是5,表示前五項就是找到的不重複的元素了


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言