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

LeetCode 575: Distribute Candies

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

基本資料
#

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

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

解題思路
#

兩個上限:只能吃 n / 2 顆,所以種類不會超過 n / 2;總共只有 len(set(candyType)) 種。兩個都達得到,所以答案是 min(Hash Table)。

我的嘗試
#

前兩版語法錯誤,接著兩版寫成 max,兩個上限只取了比較寬鬆的那個:[4, 0] 回傳 2,但只能吃 1 顆。改成 min 就 AC 了。

正確解法
#

class Solution:
    def distributeCandies(self, candyType: List[int]) -> int:
        return min(len(candyType) // 2, len(set(candyType)))

複雜度
#

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

要特別避免的錯誤
#

  • 兩個上限都要滿足,取 min。

面試口說整理
#

能吃的種類同時受限於只能吃一半、以及總共只有幾種,所以答案是兩者的較小值。時間 O(n)。

相關文章

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 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 解題筆記:雜湊表記錄每個值最後一次出現的位置,只需要跟最近的那次比距離
LeetCode 169: Majority Element
·1 分鐘
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 解題筆記:Boyer-Moore 投票,不同的數兩兩抵消,最後留下的就是出現超過一半的那個
LeetCode 1: Two Sum
·1 分鐘
LeetCode Easy Array Hash-Table
LeetCode 1 解題筆記:一邊掃一邊把看過的數存進雜湊表,查 target - x 有沒有出現過;先查再存,同一個元素才不會用兩次