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.
LeetCode:链接
二分法:每次从中间卡一半相乘看是否满足要求,这样才能让搜索的时间变短。最后返回的是high指针。
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
low = 0
high = x
while low <= high:
mid = (low + high) // 2
temp = mid * mid
if temp < x:
low = mid + 1
elif temp > x:
high = mid - 1
else:
return mid
return high
牛顿迭代法:我们现在要求的是x的平方根,即x**0.5 = t,那么x = t^2,我们可以设一个函数f(t)=t^2- x ,令f(t)=0,很明显解t就是x的平方根,在图里表示为与X轴的交点横坐标。而我们要做的就是求出这个交点。手段是取图像上一个初始点(x,f(x)),作它的切线,切线与X轴交点横坐标为X0,接下来我们又作(X0,f(X0))的切线,有没有发现,我们作的切线再逐渐向左偏,切线与X轴的交点也慢慢接近图像与X轴的交点,一直重复以上作切线过程,最后它们会无限逼近,到最后f(Xn)近似等于0(i从0到n),那么我们就可以认为Xn就是要求的平方根。
y1-f(x0) = f'(x0)(x1-x0),f(x0) = x0^2 - x,f'(x0) = 2x0,令y1 = 0,则递推式就是x1 = (x0 + x / x0) / 2,直到x^2和x的差值小于0.1。
class Solution:
def mySqrt(self, x: int) -> int:
x0 = x
while abs(x0 ** 2 - x) > 0.1:
x0 = (x0 + x / x0) / 2
return int(x0)