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

LeetCode 961: N-Repeated Element in Size 2N Array

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

基本資料
#

難易度: easy 第一次嘗試:2022-09-26

  • 提交紀錄:Accepted ×3

解題思路
#

長度 2n 的陣列有 n + 1 種數,其中一個出現 n 次,其他都只出現一次。所以邊掃邊放進集合,第一個重複的數就是答案(Hash Table)。O(1) 空間的做法:重複 n 次的數一定會在某個距離 3 以內的位置對上自己。

我的解法
#

class Solution:
    def repeatedNTimes(self, nums: List[int]) -> int:
        seen = set()
        for x in nums:
            if x in seen:
                return x
            seen.add(x)

複雜度
#

時間 O(n),空間 O(n)。

要特別避免的錯誤
#

  • 只有答案會重複,所以不用真的數到 n 次。

面試口說整理
#

其他數都只出現一次,所以第一個出現第二次的數就是答案,我邊掃邊放進集合。時間 O(n)。

相關文章

LeetCode 804: Unique Morse Code Words
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 804 解題筆記:把每個單字轉成摩斯碼字串,放進集合後算有幾種
LeetCode 594: Longest Harmonious Subsequence
·1 分鐘
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 解題筆記:子序列不用連續,所以只要計數,每個 x 看 x 和 x + 1 的次數加起來
LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集
LeetCode 350: Intersection of Two Arrays II
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 解題筆記:保留重複次數的交集,Counter 相交(&)取兩邊次數的較小值
LeetCode 929: Unique Email Addresses
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 929 解題筆記:用 @ 切開,只處理 local 的部分(+ 之後丟掉、去掉 .),接回 domain 後放進集合