LeetCode 0069.のSqrt [パイソン] [イージー二部(x)はx [平方根]
問題
実装int sqrt(int x)
。
計算の平方根を返すX、xは非負の整数であることが保証されます。
戻り型が整数であるため、桁が切り捨てられ、その結果の整数部のみが返されます。
例1:
Input: 4
Output: 2
例2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
問題
実装int sqrt(int x)
の機能を。
計算と戻るxは前記平方根をxは非負の整数です。
戻り型が整数であるため、結果の整数部は、小数部を切り捨て保持します。
例1:
输入: 4
输出: 2
例2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
思考
アクトワン:
バイナリ検索
典型的二分题目。注意返回值要是整数。
アクトII:
ニュートン反復法
詳細については、こちらの記事を参照してください:ニュートン反復法は、迅速平方根を見つけること。
令f(res) = res^2 - x,则sqrt(x)等价于求f(res)的根
初始假设答案 res = x
每一次迭代,令 res = (res + x / res) / 2
新的 res 值为当前 res 值对应的函数切线与 x 轴的交点横坐标,这就是牛顿迭代的本质。
同法III:
ライブラリとの直接の機能。
時間の複雑さ: O(logN個)
複雑スペース: O(1)
Pythonコード
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# solution one: binary search
low, high, mid = 0, x, x / 2
while low <= high:
if mid ** 2 > x:
high = mid - 1
else:
low = mid + 1
mid = (low + high) / 2
return int(mid)
# # solution two: Newton's method
# res = x
# while res * res > x:
# res = (res + x / res) / 2
# return int(res)
# # solution three: math
# import math
# return int(math.sqrt(x))