題目出處
難度
medium
個人範例程式碼
class Solution:
"""
@param a: A 32bit integer
@param b: A 32bit integer
@param n: A 32bit integer
@return: An integer
"""
def fast_power(self, a: int, b: int, n: int) -> int:
ans, tmp = 1, a
while(n > 0):
if(n % 2 == 1):
ans = (ans * tmp) % b
tmp = (tmp * tmp) % b
n = n // 2
else:
return ans % b
算法說明
- 有非常類似的問題,詳細說明可參考:【Leetcode】python – [50] Pow(x, n) 個人解法筆記
核心概念為,將 n 次方拆成二進位的方式計算 (這樣就不用重複算)
例如 9 = 8 + 0 + 0 + 1,
我們只重複計算 1^2^2^2^2…. 可以減少一半的計算次數,複雜度為 O(n) -> O(logN)
另外處理負數要特別注意。
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
input handling
處理輸入 n = 0 ,return 1,
與輸入 n < 0 ,作負數處理。
Boundary conditions
循環直到當 n 0 時 ( 1//2 = 0 )
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 | Python | |||
50 | Pow(x, n) | Binary Serach | Python |