NeetCode #265LC-69EasyBinary SearchNC 250
← Back to All Problems#265 · #69 · Sqrt(x)(x 的平方根)
📌 Problem Statement & Constraints
Given a non-negative integer
x, return the square root of x rounded down to the nearest integer. You must not use any built-in exponent function or operator. Constraints: 0 <= x <= 2^31 - 1.💡 Core Algorithmic Approaches
- Binary search for the largest integer
kwithk * k <= x. - Use the upper-bias midpoint
(lo + hi + 1) // 2together withlo = mid/hi = mid - 1, which finds the last valid value. - The range is
[0, x], sincexitself bounds the answer. - Newton's method converges faster in practice but binary search is the clearest answer.
💻 Benchmark Python3 Implementation
class Solution:
def mySqrt(self, x: int) -> int:
lo, hi = 0, x
while lo < hi:
mid = (lo + hi + 1) // 2 # upper-biased to avoid an infinite loop
if mid * mid <= x:
lo = mid # mid is valid -> keep searching right
else:
hi = mid - 1
return lo
# Newton's method: quadratic convergence
class Solution2:
def mySqrt(self, x: int) -> int:
if x < 2:
return x
r = x
while r * r > x:
r = (r + x // r) // 2 # integer Newton step
return r⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log x) for binary search; O(log log x) iterations for Newton's method.
💾 Space Complexity
O(1): a few scalars.
⚠️ Interview Pitfalls & Follow-ups
- Using the lower-biased midpoint
(lo + hi) // 2withlo = mid: this loops forever whenhi == lo + 1. The upper bias is required. - Using
math.sqrt: explicitly forbidden by the problem. - Returning the float result: the answer is an integer (floor of the square root).
- Overflowing in fixed-width languages:
mid * midcan exceed 32 bits for largex; Python is safe.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
x 的平方根
给你一个非负整数 x,计算并返回 x 的 算术平方根 。由于返回类型是整数,结果只保留 整数部分 ,小数部分将被舍去。注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x 0.5 。约束:0 ≤ x ≤ 2^31 − 1。
核心要点
- 二分查找平方根(标准解) :在 [0, x] 上二分,找「满足 mid² ≤ x 的最大 mid」,即答案。
- 模板选择 :这是「找最后一个满足条件的位置」,用「记录答案」或「结束时返回 r」的写法。
- 为什么返回 r :循环结束时 l = r + 1 ,而 r 恰好是最后一个满足 mid² ≤ x 的值。
- 禁止使用内置函数 : x 0.5 与 math.sqrt 会被判为作弊,且浮点结果在 x 接近 2^31 时可能因精度丢失而出错。
常见陷阱
- 返回 l 而非 r :循环结束时 l 已越界(指向第一个不满足的位置),答案在 r 。
- 用 mid 2 或 math.isqrt : 不算「内置指数函数」吗? x 0.5 是浮点指数,被禁止; mid 2 是整数乘法,通常允许,但为保险用 mid * mid 。 math.isqrt 是一行答案但违背题目意图。
- x = 0 的边界 :二分 [0, 0] 会得到 mid = 0, 0 <= 0 成立,l = 1,循环结束返回 r = 0,正确。
- 用浮点 sqrt 后取整 : int(math.sqrt(x)) 在 x = 2^31 − 1 等大数上可能因浮点精度返回偏小的值,需要额外的修正逻辑。
参考实现
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 # r 是最后一个满足 mid*mid <= x 的值
# 也可用牛顿迭代(收敛更快,但二分更易写对):
# if x < 2: return x
# r = x
# while r * r > x:
# r = (r + x // r) // 2
# return r