题目描述:
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
例子:
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
思路:
第一想法肯定是利用x2寻找答案,并且通过int去掉小数位。但是这样太过简单。
重点说的是利用binary search方法寻找答案。并且二次方根必然会小于这个数的一半当这个数大于2时,所以我们只需找到左右边界l和r,计算出这两个边界的中间值mid进行mid2的计算,如果结果大于x则右边界移动到mid的位置,如果小于x则左边界移动到mid位置。以此循环直到左右边界重合。
代码:
class Solution:
def mySqrt(self, x: int) -> int:
if x < 2: return x
l = 1
r = x // 2
while l <= r:
mid = l + (r-l)//2
if mid*mid > x:
r = mid - 1
else:
l = mid + 1
return r
解释:
由于是在左边界改变时取等,所以输出的右边界为准确值。如果返回左边界则需要减去1.