Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

求一个数的开方,binary search on result 二分结果的典型。

对于0和1直接返回1。后面的left = 1 ,right 为 x/2。代码如下:

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 2:
            return x
        l = 1
        r = x/2
        while l+1 < r:
          mid = l + (r-l)/2
          if mid **2 == x:
              return mid
          if mid**2 > x:
              r = mid
          else:
              l = mid
         
        return r if r**2 <= x else l  

时间复杂度O(logn),空间复杂度为O(1)。

原文地址:https://www.cnblogs.com/sherylwang/p/5496321.html