[leetcode:python]69.Sqrt(x)

来源:互联网 发布:如何建设企业文化 知乎 编辑:程序博客网 时间:2024/06/05 14:56

题目:求平方根
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

感觉两个方法一样。。

0 0