[LeetCode] 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++ or x ** 0.5 in python.
Example 1:
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.
Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since we round it down to the nearest integer, 2 is returned.
Constraints:
0 <= x <= 231 - 1
求平方根。
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
思路
比较直观的思路就是线性扫描,但是这道题的考点/最优解应该是二分法。
二分法的具体做法是用 X/2 试试看是不是 X 的平方根。如果找不到(比如26就没有平方根),就输出最接近这个数平方根的那个整数。
影子题367,思路一模一样。
复杂度
时间O(logn), worse case O(n)
空间O(1)
代码
Java实现 - 这里为了处理整型越界问题,我把所有数字都改成long型再判断
1 |
|
JavaScript实现
1 |
|