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

LeetCode 69: Sqrt(x)

·1 分鐘· ·
LeetCode Easy Math Binary-Search Newtons-Method
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-05-12

  • 提交紀錄:Wrong Answer → Accepted → Wrong Answer → Accepted

解題思路
#

要找最大的 k 使 k² <= x(Binary Search 模板四)。閉區間 [0, x] 二分:mid² <= x 就往右找更大的,否則往左。迴圈結束時 r 停在最後一個滿足的位置。

我的嘗試
#

2022 年 5 月第一版用了 /,mid 是浮點數,例如 x = 5 回傳 1.5;改成 // 就 AC 了。8 月重寫時一版的結果多了 1,例如 x = 5 回傳 3。

正確解法
#

class Solution:
    def mySqrt(self, x: int) -> int:
        l, r = 0, x
        while l <= r:
            mid = (l + r) // 2
            if mid * mid <= x:
                l = mid + 1
            else:
                r = mid - 1
        return r

複雜度
#

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

要特別避免的錯誤
#

  • mid 要用整數除法。
  • 答案是無條件捨去,要回傳最後一個 mid² <= x 的值。

面試口說整理
#

我在 0 到 x 之間二分,平方不超過 x 就往右找,超過就往左;結束時右界就是最大的平方不超過 x 的整數。時間 O(log x)。

相關文章

LeetCode 35: Search Insert Position
·1 分鐘
LeetCode Easy Array Binary-Search
LeetCode 35 解題筆記:找第一個 >= target 的位置(lower bound);半開區間 [l, r) 要配 r = mid,不能寫 r = mid - 1
LeetCode 66: Plus One
·1 分鐘
LeetCode Easy Array Math
LeetCode 66 解題筆記:從最後一位往前加一,遇到 9 變 0 繼續進位,全部都是 9 時前面補 1
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 9: Palindrome Number
·1 分鐘
LeetCode Easy Math
LeetCode 9 解題筆記:負數一定不是回文;不轉字串的話,把後半段的數字反轉,跟前半段比較
LeetCode 13: Roman to Integer
·1 分鐘
LeetCode Easy Hash-Table Math String
LeetCode 13 解題筆記:從左到右加每個符號的值,如果它比右邊的符號小就改成減
LeetCode 27: Remove Element
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 27 解題筆記:寫入指標只寫不等於 val 的數,最後回傳寫入的個數