【LeetCode】69.Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

【题目分析】

题目要求实现求平方根(舍小数取整)函数

如果直接从1开始遍历到x寻找,会超时。

问题的症结便集中在怎样最大限度缩小遍历次数

【思路分析】

使用二分查找的思想,缩小查找范围[l,r]

【参考代码_60ms】

    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x==0:
            return 0
        if x<4:
            return 1
        l,r=0,x
        while l<r:
            mid=(l+r)//2
            if x>=(mid*mid) and x<(mid+1)*(mid+1):
                return mid
            if x>(mid*mid):
                l=mid
            else:
                r=mid
        return mid

(ps,最暴力方法:446 / 1017 test cases passed.

    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x==0:
            return 0
        if x==1:
            return 1
        for i in range(1,x):
            if i*i<=x and (i+1)*(i+1)>x:
                return i

和寻找规律法:131 / 1017 test cases passed.

    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x==0:
            return 0
        if x==1 or x==2 or x==3:
            return 1
        count=1
        for i in range(2,x):
            if i%2==0:
                continue
            count+=1
            left=(1+i)*count/2
            right=(1+i+2)*(count+1)/2
            if x>=left and x<right:
                return count
均为 Time Limit Exceeded

)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值