題目出處
2244. Minimum Rounds to Complete All Tasks
難度
medium
個人範例程式碼
class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
# 1: -1 round
# 2: 1 round
# 3: 2 rounds
# 3k: k rounds
# 3k+1: 4=3(k-1)+2+2, k+1 times
# 3k+2: 5=3(1)+2, k+1 times
counters = Counter(tasks)
ans = 0
for num_of_task in counters.values():
if num_of_task <= 1:
return -1
else:
# 3 = 1
# 4 = 2
# 5 = 2
# 6 = 2
ans += (num_of_task+2)//3
return ans
算法說明
這題考的是數學歸納法的概念,比較是數學的範圍
我們推論:
- 1: -1 round
- 2: 1 round
- 3: 2 rounds
- 3k: k rounds
- 3k+1: 4=3(k-1)+2+2, k+1 times
- 3k+2: 5=3(1)+2, k+1 times
而為了計算方便,我們可以做一些使計算上方便的技巧。
- 3 = 1
- 4 = 2
- 5 = 2
- 6 = 2
我們透過移動 k+2 使得 // 3 後能夠直接得到我們要的數字。
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
input handling
x
Boundary conditions
只要發現其中一個任務不可能執行完成,提早 return -1。
Reference
⭐ Leetcode 解題紀錄 ⭐ | 題型 | 資料結構 | Python Solution | C++ Solution | Note | |
---|---|---|---|---|---|---|
⭐BFS 相關題型 ⭐ | ||||||
104 | Maximum Depth of Binary Tree | BFS (分層) | Python | |||
94 | Binary Tree Inorder Traversal | BFS (分層) | Tree | Python | 內含 處理 Tree 樹問題的重點 | |
102 | Binary Tree Level Order Traversal | BFS (分層) | Tree | Python | ||
103 | Binary Tree Zigzag Level Order Traversal | BFS (分層) | Tree | Python | ||
107 | Binary Tree Level Order Traversal II | BFS (分層) | Tree | Python | ||
133 | Clone Graph | BFS (分層) | Graph | Python | Graph 的基本操作 #重要題型 | |
127 | Word Ladder | BFS (分層), DFS | Graph | Python | ||
[Lint] 127 | Topological Sorting | BFS (拓撲) | Python | 內有 indegree, outdegree 介紹 #重要題型 | ||
207 | Course Schedule | BFS (拓樸) | Graph | Python | ||
210 | Course Schedule II | BFS (拓樸) | Graph | Python | ||
[Lint] 892 | Alien Dictionary | BFS (拓樸) | Graph | Python | ||
[Lint] 431 | Connected Component in Undirected Graph | BFS (連通塊) | Graph | Python | 內含 BFS 模板 #重要題型 | |
1091 | Shortest Path in Binary Matrix | BFS (最短路徑) | Matrix | Python | ||
⭐ Binary Serach 相關題型 ⭐ | ||||||
33 | Search in Rotated Sorted Array | Binary Serach | Array | Python | #重要題型 | |
34 | Find First and Last Position of Element in Sorted Array | Binary Serach |