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

LeetCode 442: Find All Duplicates in an Array

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

基本資料
#

難易度: medium 第一次嘗試:2026-01-31

  • 提交紀錄:Time Limit Exceeded ×2 → Accepted

解題思路
#

值都在 1..n,所以 nums[v - 1] 剛好可以當 v 的「出現過」標記(Hash Table 模板二):

  • 第一次遇到 v,把 nums[v - 1] 變成負的。
  • 再遇到 v 時 nums[v - 1] 已經是負的,v 就是重複的。

讀值時要取絕對值,因為它本身可能已經被別的數標記成負的。

我的嘗試
#

前兩版用 -num in nums 檢查,在 list 上用 in 是 O(n),整體 O(n²),TLE。改成用 index 直接查就 AC 了。

正確解法
#

class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        res = []
        for x in nums:
            i = abs(x) - 1
            if nums[i] < 0:
                res.append(abs(x))
            else:
                nums[i] = -nums[i]
        return res

複雜度
#

時間 O(n),額外空間 O(1)(不算輸出)。

要特別避免的錯誤
#

  • list 的 in 是線性搜尋。
  • 讀值時要取絕對值。

面試口說整理
#

值在 1 到 n,我用 nums[v - 1] 的正負號記錄 v 有沒有出現過。第一次遇到就把它變負,第二次遇到時已經是負的,就把 v 加進答案。時間 O(n)、額外空間 O(1)。

相關文章

LeetCode 923: 3Sum With Multiplicity
·3 分鐘
LeetCode Medium Two-Pointers Sorting Hash-Table Counting Array
LeetCode 923 解題筆記:排序後固定第一個數、對撞指針找另外兩個;兩端值相同時用組合數一次算完,不同時把兩端各自的重複數相乘
LeetCode 2537: Count the Number of Good Subarrays
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2537 解題筆記:加入 x 會多出 cnt[x] 對相同的 pair,移出時少 cnt[x] - 1 對;「至少 k 對」的計數視窗,count += left
LeetCode 2875: Minimum Size Subarray in Infinite Array
·1 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 2875 解題筆記:先拿掉 target // sum 個完整週期,剩下的餘數比一整圈小,一定能在兩份 nums 接起來的陣列裡用滑動視窗找到
LeetCode 2831: Find the Longest Equal Subarray
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Binary-Search Array
LeetCode 2831 解題筆記:對每個值,把它出現的位置列出來;在位置列表上滑動視窗,要刪的數量 = 位置跨度 − 這個值的個數
LeetCode 3795: Minimum Subarray Length With Distinct Sum At Least K
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 3795 解題筆記:求最短的可變視窗;同一個值只算一次,記錄每個值最後出現的位置,左邊界移出的是最後一次出現才扣掉
LeetCode 3679: Minimum Discards to Balance Inventory
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 解題筆記:規則已經決定哪些要丟,直接模擬;長度 w 的視窗只計算「留下來」的到貨,被丟掉的離開視窗時不能再扣