[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<x:
                start=mid
            else:
                end=mid
        
        if end*end==x:
            return end
        else:
            return start

牛顿法:

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

牛顿法
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • 冬日的阳光,带着刺冷的温暖, 孤高的杨树像个勇士,不畏风寒, 挺拔地立在道路两旁, 没有喋喋不休的麻雀,在树枝上声...
    卖小妞的饼干阅读 1,418评论 0 0
  • 不只喜欢荷花的美丽和它的食用价值,更崇尚它“出淤泥而不染,濯清涟而不妖”的品格。
    小猪崽崽阅读 1,540评论 0 2
  • 这些天无论对学习还是生活都有了新的认识,学习要严谨,全力以赴。生活中要更多的学会尊重世界,用包容的心面对,并且理解...
    追逐梦想的金玉阅读 3,764评论 0 0

友情链接更多精彩内容