項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 search-input 尚未註冊或是沒有一個 view.php 檔案.

【Lintcode】python – [140] Fast Power 個人解法筆記

題目出處

140 · Fast Power

難度

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

算法說明

核心概念為,將 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 SolutionC++ SolutionNote
⭐BFS 相關題型 ⭐
104Maximum Depth of Binary TreeBFS (分層)Python
94Binary Tree Inorder TraversalBFS (分層)TreePython 內含 處理 Tree 樹問題的重點
102Binary Tree Level Order TraversalBFS (分層)TreePython
103Binary Tree Zigzag Level Order TraversalBFS (分層)TreePython
107Binary Tree Level Order Traversal IIBFS (分層)TreePython
133Clone GraphBFS (分層)GraphPython Graph 的基本操作 #重要題型
127Word LadderBFS (分層), DFSGraphPython
[Lint] 127Topological SortingBFS (拓撲)Python
內有 indegree, outdegree 介紹 #重要題型
207Course ScheduleBFS (拓樸)GraphPython
210Course Schedule IIBFS (拓樸)GraphPython
[Lint] 892Alien DictionaryBFS (拓樸)GraphPython
[Lint] 431Connected Component in Undirected GraphBFS (連通塊)GraphPython 內含 BFS 模板 #重要題型
1091Shortest Path in Binary MatrixBFS (最短路徑)MatrixPython
⭐ Binary Serach 相關題型 ⭐
33Search in Rotated Sorted ArrayBinary SerachArrayPython #重要題型
34Find First and Last Position of Element in Sorted ArrayBinary SerachPython
50Pow(x, n) Binary SerachPython