题目:求平方根
Implement int sqrt(int x).
Compute and return the square root of x.
方法一:性能62ms
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
#二分查找
if x < 2:
return x
low, high = 1, x/2
last = 0
while low <= high:
mid = (low + high)/2
if mid * mid > x:
high = mid -1
elif mid * mid < x:
low = mid + 1
last = mid
else:
return mid
return last
方法二:性能45ms
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left = 0
right = x
while(left <= right):
mid = (left + right)/2
if(mid*mid < x):
left = mid + 1
elif(mid*mid > x):
right = mid -1
else:
return mid
return left - 1
感觉两个方法一样。。