#69
Easy
二分搜索

Sqrt(x)

计算 x 的整数平方根。

MathBinary Search

题目定位

这是标准的答案空间二分,因为目标是找最大的 mid,使得 mid^2 <= x。

关键观察

你不是在数组位置上二分,而是在可行答案边界上二分。

目标复杂度

O(log x) / O(1)

这题的解法思路怎么拆

1

这是标准的答案空间二分,因为目标是找最大的 mid,使得 mid^2 <= x。

2

你不是在数组位置上二分,而是在可行答案边界上二分。

3

先用自然语言写出单调判定条件。

4

确保搜索区间一定覆盖答案。

参考实现

Python
# Generic pattern template
# Find first position where check(mid) is true
left, right = 0, n
while left < right:
    mid = left + (right - left) // 2
    if check(mid):
        right = mid
    else:
        left = mid + 1
return left

常见坑点

warning

计算 mid * mid 时溢出。

warning

x 不是完全平方数时,返回了错误边界。

高频追问

如何优雅避免溢出?

能把它改写成 first false / last true 吗?

继续刷相关题

先把 二分搜索 这个模式刷成体系,再去做更难变体。

view_week回到模式页
LeetCode 69. Sqrt(x) 题解思路 | Interview AiBox