Python LeetCode 69. Sqrt(x) 二分法和牛頓迭代法
二分法
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
l, r, result = 0, x, -1
while l <= r:
mid = (l + r) // 2
if mid * mid <= x:
result = mid
l = mid + 1
else:
r = mid - 1
return result
牛頓迭代法
https://leetcode-cn.com/problems/sqrtx/solution/niu-dun-die-dai-fa-by-loafer/
參考上面的鏈接,其實上面寫的我看不太懂,之後弄懂了,就我寫一下我自己的理解。借一下圖
這個地方舉例子非常好,很容易看出來算的很快
原文這個地方我是沒太懂的一開始。
沒懂的是x-f(x)/(2x)這一句,其實這一句,可以分開來看,f(x)/(2x)其實就是f(x)/f(x)的導數,那麼幾何含義就是變化量,
圖片中紅色的部分。之後就是代入公式化簡了,注意先算/再算減號。
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return 0
a, x0 = float(x), float(x)
while True:
xi = 0.5 * (x0 + a / x0)
if abs(x0 - xi) < 1e-7:
break
x0 = xi
return int(x0)