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

LeetCode 50: Pow(x, n)

·1 分鐘· ·
LeetCode Medium Math Recursion
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2022-11-14

  • 提交紀錄:Accepted(一次通過)

解題思路
#

快速冪(Math 模板八):n 是偶數時 x^n = (x²)^(n/2),奇數時再多乘一個 x,每次 n 減半,只要 O(log n) 次乘法。n < 0 時先把 x 換成 1 / x、n 換成 -n。迭代版本是看 n 的二進位:哪一位是 1,就把目前的 x^(2^k) 乘進答案。

我的嘗試
#

一次 AC,當時用的是遞迴版:n < 0 回傳 1 / myPow(x, -n),奇數 x * myPow(x, n - 1),偶數 myPow(x * x, n // 2)。

正確解法
#

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n < 0:
            x, n = 1 / x, -n
        res = 1.0
        while n:
            if n & 1:
                res *= x
            x *= x
            n >>= 1
        return res

複雜度
#

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

要特別避免的錯誤
#

  • 一次乘一個 x 是 O(n),n 到 2^31 會超時。
  • 負的指數要取倒數。
  • n = 0 時答案是 1。

面試口說整理
#

我用快速冪,看 n 的二進位,每一位是 1 就把目前的 x 乘進答案,x 每次平方、n 每次右移一位;n 是負數時先換成 1 / x 和 -n。時間 O(log n)。

相關文章

LeetCode 2: Add Two Numbers
·1 分鐘
LeetCode Medium Linked-List Math Recursion
LeetCode 2 解題筆記:位數是反著存的,從頭開始逐位相加帶進位;迴圈跑到兩條都走完而且沒有進位為止
LeetCode 264: Ugly Number II
·1 分鐘
LeetCode Medium Hash-Table Math Dynamic-Programming Heap-Priority-Queue
LeetCode 264 解題筆記:三個指針分別指向下一個要乘 2、3、5 的醜數,每次取最小的,相等的指針都要前進
LeetCode 227: Basic Calculator II
·1 分鐘
LeetCode Medium Math String Stack
LeetCode 227 解題筆記:先把數字讀完整,遇到運算子時處理上一個運算子:+ - 把數放進 stack(減號放負數),* / 直接跟頂端算
LeetCode 189: Rotate Array
·1 分鐘
LeetCode Medium Array Math Two-Pointers
LeetCode 189 解題筆記:先 k %= n,再用三次反轉:整個反轉、前 k 個反轉、後 n - k 個反轉;O(1) 額外空間
LeetCode 204: Count Primes
·1 分鐘
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 解題筆記:埃氏篩,只用質數 p 從 p² 開始把倍數劃掉,外層只要到 √n
LeetCode 48: Rotate Image
·1 分鐘
LeetCode Medium Array Math Matrix
LeetCode 48 解題筆記:順時針轉 90 度 = 先轉置再把每一列左右反轉,兩步都可以原地做