LeetCode 69 Sqrt(x)

时间:2019-08-25 18:02:16   收藏:0   阅读:80

题目-x 的平方根

【英文版】https://leetcode.com/problems/sqrtx/
【中文版】https://leetcode-cn.com/problems/sqrtx/

实现?int sqrt(int x)?函数。
计算并返回?x?的平方根,其中?x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例

输入: 8 ?输出: 2
说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
"""
:type x: int
:rtype: int
"""

暴力求解

遍历x//2+1,如果第i个数刚好使得i*i<=x and (i+1)*(i+1)>x则返回i
但是这种方法会用Runtime Error。
★ 时间复杂度:\(O(x//2+1)\)
★ 空间复杂度:\(O(1)\)


Brute Force-python


class Solution(object):
    def mySqrt(self, x):
        for i in range(1,x//2+1):
            if i*i<=x and (i+1)*(i+1)>x: return i

Runtime Error

二分查找

一个数的平方根最小是0(x == 0),最大是x//2+1(+1是为了避免x == 1,整除2为0的情况)。
二分查找的注意细节可看这篇博文:LeetCode 35 Search Insert Position


Binary Search-python


class Solution(object):
    def mySqrt(self, x):
        left = 0
        right = x // 2 + 1
        while left < right:
            mid = left + (right - left + 1) // 2
            if mid * mid > x:
                right = mid - 1
            elif (mid + 1) * (mid + 1) > x:
                return mid
            else:
                left = mid
        return left

Runtime: 20 ms, faster than 77.82% of Python online submissions for Sqrt(x).
Memory Usage: 11.6 MB, less than 96.08% of Python online submissions for Sqrt(x).

同类型题目

  1. [LeetCode 35 Search Insert Position](https://leetcode.com/problems/search-insert-position/)
  2. [LeetCode 704 Binary Search](https://leetcode.com/problems/binary-search/)
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!