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

LeetCode 350: Intersection of Two Arrays II

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

基本資料
#

難易度: easy 第一次嘗試:2022-08-23

  • 提交紀錄:Accepted ×4

解題思路
#

每個值出現的次數是兩邊次數的較小值。Counter 的 & 就是「每個 key 取較小的次數」(Hash Table)。陣列已排序的話也可以用雙指針。

我的解法
#

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list((Counter(nums1) & Counter(nums2)).elements())

複雜度
#

時間 O(m + n),空間 O(min(m, n))。

要特別避免的錯誤
#

  • 跟 LC 349 不同,這題要保留重複。

面試口說整理
#

每個值的次數是兩邊次數的較小值,所以我用 Counter 的交集再展開成 list。時間 O(m + n)。

相關文章

LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集
LeetCode 268: Missing Number
·1 分鐘
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 解題筆記:0 到 n 的總和減掉陣列總和就是缺的那個;缺的可能是 0
LeetCode 283: Move Zeroes
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 283 解題筆記:寫入指標只在遇到非零數時前進,跟它交換;零自然被推到後面
LeetCode 202: Happy Number
·1 分鐘
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 解題筆記:一直取位數平方和,會走到 1 或進入環;用集合記看過的數,或用快慢指針判圈
LeetCode 217: Contains Duplicate
·1 分鐘
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 解題筆記:轉成 set 後長度變短就代表有重複
LeetCode 219: Contains Duplicate II
·1 分鐘
LeetCode Easy Array Hash-Table Sliding-Window
LeetCode 219 解題筆記:雜湊表記錄每個值最後一次出現的位置,只需要跟最近的那次比距離