【LeetCode】69. Sqrt(x) Python3解法

题目描述:

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.

思路:

第一想法肯定是利用x2寻找答案,并且通过int去掉小数位。但是这样太过简单。
重点说的是利用binary search方法寻找答案。并且二次方根必然会小于这个数的一半当这个数大于2时,所以我们只需找到左右边界l和r,计算出这两个边界的中间值mid进行mid
2的计算,如果结果大于x则右边界移动到mid的位置,如果小于x则左边界移动到mid位置。以此循环直到左右边界重合。

代码:

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

解释:

由于是在左边界改变时取等,所以输出的右边界为准确值。如果返回左边界则需要减去1.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值