Leecode 0069. Sqrt(x)
69. Sqrt(x)
Given a non-negative integer x
, return the square root of x
rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator.
- For example, do not use
pow(x, 0.5)
in c++ orx ** 0.5
in python.
Example 1:
1 | Input: x = 4 |
Example 2:
1 | Input: x = 8 |
Constraints:
0 <= x <= 231 - 1
解法解析
计算平方根问题可以通过二分查找高效解决,时间复杂度为 O (log x),空间复杂度为 O (1)。
核心思路
问题本质是找到最大的整数 mid
使得 mid \* mid <= x
,这个整数就是 x 的平方根的整数部分。
算法步骤
特殊情况处理:当 x 为 0 或 1 时,直接返回 x 本身
设置查找边界:对于 x > 1,平方根一定在 [1, x/2] 范围内,这是因为对于 x > 4,x/2 的平方已经大于 x
二分查找过程:
- 计算中间值
mid
,使用left + (right - left) / 2
避免整数溢出 - 计算
mid * mid
,使用long long
类型防止乘法结果溢出 - 比较平方结果与 x:
- 若相等,直接返回 mid(找到精确的整数平方根)
- 若小于 x,记录当前 mid 为候选结果,并向右继续查找更大的可能值
- 若大于 x,向左查找更小的值
返回结果:循环结束后,返回记录的最大满足条件的整数
1 | #include <iostream> |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.