↓快轉到主要內容
  1. LeetCode/

LeetCode 3731: Find Missing Elements

·1 分鐘· ·
LeetCode Easy Hash-Table Sorting Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-11-02

  • 提交紀錄:Accepted(一次通過)

解題思路
#

原本的範圍是 [min, max],而且兩端還在陣列裡。枚舉範圍內的每個整數,不在陣列裡的就是缺少的;由小到大枚舉,結果自然排好。

查詢要用集合(Hash Table 模板一)。

我的解法
#

我當時直接用 i not in nums,在 list 上查詢每次 O(n);題目範圍很小所以也過了。改成集合:

class Solution:
    def findMissingElements(self, nums: List[int]) -> List[int]:
        seen = set(nums)
        return [x for x in range(min(nums), max(nums)) if x not in seen]

max 一定在陣列裡,所以 range 不包含它也沒關係。

複雜度
#

時間 O(n + R),R 是 max - min,空間 O(n)。

要特別避免的錯誤
#

  • 在 list 上用 in 是線性搜尋,範圍大時要換成集合。

面試口說整理
#

最小值和最大值一定還在,所以我把陣列轉成集合,枚舉兩者之間的每個整數,不在集合裡的就是缺少的。時間 O(n + R)。

相關文章

LeetCode 594: Longest Harmonious Subsequence
·1 分鐘
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 解題筆記:子序列不用連續,所以只要計數,每個 x 看 x 和 x + 1 的次數加起來
LeetCode 2099: Find Subsequence of Length K With the Largest Sum
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
LeetCode 2099 解題筆記:選出最大的 k 個數(連同 index),再按 index 排回原本的順序
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 分鐘
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 解題筆記:每次操作會讓最小的正數那一群變成 0,所以次數就是不同的正數有幾種
LeetCode 1122: Relative Sort Array
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Counting-Sort
LeetCode 1122 解題筆記:計數後先按照 arr2 的順序輸出,剩下的數由小到大接在後面
LeetCode 888: Fair Candy Swap
·1 分鐘
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 解題筆記:交換 x 和 y 後總和相等,代表 y = x + (sumB - sumA) / 2;把 B 放進集合,逐一檢查 A 的 x
LeetCode 645: Set Mismatch
·1 分鐘
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 解題筆記:用總和算:missing = 1..n 的和 - set 的和,duplicate = 陣列總和 - set 的和