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

LeetCode 599: Minimum Index Sum of Two Lists

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

基本資料
#

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

  • 提交紀錄:Runtime Error ×3 → Wrong Answer ×4 → Accepted → Runtime Error → Accepted ×4

解題思路
#

把 list1 存成「字串 → index」的雜湊表(Hash Table),掃 list2 時遇到共同的字串就算 index 和。比目前最小的還小就重設答案,相等就加進答案。

我的嘗試
#

這題提交了 13 次:

  • 前三版是語法錯誤,第四版忘了 return。
  • 接下來三版自己維護 i 當 index,但迴圈裡忘了 i += 1,list1 的每個字串 index 都是 0:["c", "e"]、["e", "c"] 兩個的 index 和都是 1,答案 ["c", "e"],回傳 ["e"]。補上就 AC 了。
  • 晚上重寫成兩個 dict 的版本時又有一次變數名稱錯誤(NameError)。

正確解法
#

class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        pos = {s: i for i, s in enumerate(list1)}
        best, res = float("inf"), []
        for j, s in enumerate(list2):
            if s in pos:
                total = pos[s] + j
                if total < best:
                    best, res = total, [s]
                elif total == best:
                    res.append(s)
        return res

複雜度
#

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

要特別避免的錯誤
#

  • 自己維護 index 時要記得加一,或直接用 enumerate。
  • list.index 每次 O(m),整體會變 O(nm)。

面試口說整理
#

我把第一個 list 的字串對應到 index 存進雜湊表,掃第二個 list 時遇到共同的字串就算 index 和,比最小值小就重設答案、相等就加進去。時間 O(n + m)。

相關文章

LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
LeetCode 575: Distribute Candies
·1 分鐘
LeetCode Easy Array Hash-Table
LeetCode 575 解題筆記:最多只能吃 n / 2 顆,種類最多 len(set),答案是兩者的較小值
LeetCode 448: Find All Numbers Disappeared in an Array
·1 分鐘
LeetCode Easy Array Hash-Table
LeetCode 448 解題筆記:把陣列本身當雜湊表,看到 x 就把 nums[x - 1] 標成負數,最後還是正數的位置就是沒出現的數
LeetCode 268: Missing Number
·1 分鐘
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 解題筆記:0 到 n 的總和減掉陣列總和就是缺的那個;缺的可能是 0
LeetCode 290: Word Pattern
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 290 解題筆記:pattern 的字元和單字要一對一對應,用兩個方向的 dict 或比較 set 大小
LeetCode 383: Ransom Note
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 383 解題筆記:ransomNote 每個字元的需求數量都不能超過 magazine 的數量;Counter 相減為空就成立