Leetcode刷题-69. x 的平方根

题目

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

备注
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sqrtx
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法1

一步步往前,效率并不高

class Solution {
    public int mySqrt(int x) {
        if (x < 2) {
            return x;
        }
        int pre = 2;
        int result = x / pre;
        while (result > (pre + 1)) {
            result = x / ++pre;
        }
        return Math.min(pre, result);
    }
}

解法2

主要是看别人的答案,用的是二分法,时间效率比较快。

解法3

与解法2区别,用除法,避免使用long(x过大时),收敛更快(能快多少,不太清楚了)

class Solution {
    public int mySqrt(int x) {
        int left = 0;
        int right = (x >>> 1) + 1;
        while (left < right) {
            int mid = (left + right + 1) >>> 1;
            int midOther = x / mid;
            if (Math.abs(midOther - mid) < 2) {
                return Math.min(mid, midOther);
            }
            if (midOther > mid) {
                left = mid;
                if (right > midOther - 1) {
                    right = midOther - 1;
                }
            } else {
                right = mid - 1;
                if (left < midOther) {
                    left = midOther;
                }

            }
        }
        return left;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值