[BinarySearch]069 Sqrt(x)

  • 分类:BinarySearch

  • 考察知识点:BinarySearch 牛顿法

  • 最优解时间复杂度:O(logn)(BinarySearch) O(?)牛顿法

  • 最优解空间复杂度:O(1)

69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

代码:

BinarySearch方法:

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        start=0
        end=x
        while(end-start>1):
            mid=(end-start)//2+start
            res=mid*mid
            if res==x:
                return mid
            elif res

牛顿法:

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        res=x
        while(res*res>x):
            res=(res+x//res)//2
        return int(res)

讨论:

1.这道题有两种解法,在面试的时候最好还是把两种解法都写上比较好
2.牛顿法的具体操作参考367题???(其实我并不打算刷到那么后面orz)(res+x//res)//2....这是什么神操作啊。。。好厉害

BinarySearch

牛顿法

你可能感兴趣的:([BinarySearch]069 Sqrt(x))