69 | Sqrt(x) | 28.60% | 开方,用二分法缩小尝试范围 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 7 16:06:06 2018
@author: vicky
"""
##import math
#
#class Solution:
# def mySqrt(self, x):
# """
# :type x: int
# :rtype: int
# """
# #return int(math.sqrt(x))
#
# #时间超过了
# for n in range(int(x/4)+4):
# if n**2>x:
# return n-1
# break
# elif n**2==x:
# return n
# break
#https://www.cnblogs.com/grandyang/p/4346413.html
#法一:二分搜索法: http://www.cnblogs.com/luoxn28/p/5767571.html
# 将查找的键和子数组的中间键作比较,
# 如果被查找的键小于中间键,就在左子数组继续查找;
# 如果大于中间键,就在右子数组中查找,
# 否则中间键就是要找的元素。
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left=0
right=int(x/2)+1
while left<=right:
mid=int((left+right)/2)
if mid**2<x: #向左子数组继续查找
if (mid+1)**2>x:
return mid
left=mid+1 #注意是mid+1不是left+1,直接把mid左边的区间不要
elif mid**2==x:
return mid
else: #向右子数组继续查找
right=mid-1 #注意是mid+1不是right-1,直接把mid右边的区间不要
# return left-1
##法二:牛顿迭代法,要求f(x)=0解,用x[n+1]=x[n]-f(x[n])/f'(x[n])来迭代
## 这里f(x)=x^2-n,则x[n+1]=x[n]-{x[n]^2-n}/{2x[n]}={x[n]+n/x[n]}/2
#
## 当x=5、7...等时有bug,迭代不出来
#class Solution:
# def mySqrt(self, x):
# """
# :type x: int
# :rtype: int
# """
# r=x
# while r*r>x:
# r=(r+x/r)/2
# return int(r)
x=0
print(Solution().mySqrt(x))