LeetCode 69. x 的平方根

阅读 97

2022-05-05

题目链接:

力扣icon-default.png?t=M3K6https://leetcode-cn.com/problems/sqrtx/

【分析】通过二分查找,判定条件为mid*mid<=target的最大值,因此是upperBound的right,缩短左区间的条件为x<mid * mid

class Solution {

    public int binarySearch(int x){
        long left = 0, right = x, mid, tmp;
        while(left <= right){
            mid = (left + right) >>> 1;
            if(x < mid * mid){
                right = mid - 1;
            }else{
                left = mid + 1;
            }
        }
        return (int)right;
    }

    public int mySqrt(int x) {
        return binarySearch(x);
    }
}

精彩评论(0)

0 0 举报