码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode二分查找之求开方

时间:2020-05-20 21:33:32      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:style   art   run   返回   返回值   mys   它的   The   一个   

正常实现

Input : [1,2,3,4,5]
key : 3
return the index : 2

Input: 4
Output: 2

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.

一个数 x 的开方 sqrt 一定在 0 ~ x 之间,并且满足 sqrt == x / sqrt。可以利用二分查找在 0 ~ x 之间查找 sqrt。

对于 x = 8,它的开方是 2.82842...,最后应该返回 2 而不是 3。在循环条件为 l <= h 并且循环退出时,h 总是比 l 小 1,也就是说 h = 2,l = 3,因此最后的返回值应该为 h 而不是 l。

public int mySqrt(int x) {
    if (x <= 1) {
        return x;
    }
    int l = 1, h = x;
    while (l <= h) {
        int mid = l + (h - l) / 2;
        int sqrt = x / mid;
        if (sqrt == mid) {
            return mid;
        } else if (mid > sqrt) {
            h = mid - 1;
        } else {
            l = mid + 1;
        }
    }
    return h;
}

 

leetcode二分查找之求开方

标签:style   art   run   返回   返回值   mys   它的   The   一个   

原文地址:https://www.cnblogs.com/ziytong/p/12926444.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!