前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q69 Sqrt(x)

Q69 Sqrt(x)

作者头像
echobingo
发布2018-04-25 16:45:14
8280
发布2018-04-25 16:45:14
举报

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:
代码语言:javascript
复制
Input: 4
Output: 2
Example 2:
代码语言:javascript
复制
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., 
and since we want to return an integer, the decimal part will be truncated.
解题思路:

此题目实现Python中 int(math.sqrt(x)) 的功能。简单方法就是从0开始循环,找到当前数的平方不大于x的但下一个数的平方大于x的数,然后返回当前数。但是这种做法时间复杂度为O(n^(1/2)),会超时。

可以借助二分查找的思想,时间复杂度降为 O(lgn)。

Python实现:
代码语言:javascript
复制
class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0 or x == 1:  # 注意 0, 1 这两个特殊的数字
            return x
        low = 0; high = x
        while low <= high:
            mid = (low + high) // 2
            if mid ** 2 <= x < (mid + 1) ** 2:
                return mid
            elif mid ** 2 > x:
                high = mid
            else:
                low = mid
        return 0

a = 8
b = Solution()  
print(b.mySqrt(a))  # 2
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example 1:
  • Example 2:
  • 解题思路:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档