[LeetCode#69] Sqrt(x)

本文介绍了一种使用二分查找算法高效计算整数平方根的方法,并详细解释了该算法的具体实现过程及其注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The problem:

Implement int sqrt(int x).

Compute and return the square root of x.

 

My analysis:

The problem could be solved amazingly by using binary search.
When using the algorithm, we should be very careful in in tackling range issues.

The following skills should be kept in mind.
1. All binary search has low pointer and high pointer, the terminating condition should be low < = high (index).

2. Unlike the problem of search in array, whose low and high pointer's initial location could be easily indetified as 0 to length - 1. In this case, the low pointer should start from "1", and the high pointer should start from "x/2 + 1"(this is a little tricky skill). (x/2 + 1) ^ 2 > x. (thus we can guarantee the answer for x in the range)

3. Since we need to check if a value is the sqrt of a target, we may rushly use mid * mid <= x (very dangerous!!!, the multiplication might lead to overflow)
if (mid * mid <= x && (mid + 1) * (mid + 1) > x)
Nicely, this could be sovled by following way: (no need to introduce complex max_value or min_value)
if (mid < = x / mid && (mid + 1) > x / (mid + 1))
we could use x directly as bound, the bound is in the range of [1, Max.value]
(we have already known the bound, unlike the situation in conversion, which we don't know the bound).

My solution:

public class Solution {
    public int sqrt(int x) {
        if (x < 0)
            return -1;
            
        if (x == 0)
            return 0; 

        int low = 1; // the low should be set to 1. it's different from the search in array.
        int high = x / 2 + 1; // the high should be set to x / 2 + 1
        int mid;
        
        while (low <= high) {
            
            mid = (high + low)/ 2;
            
            if ((x / mid >= mid) && ((mid + 1) > x / (mid + 1))) { //to avoid overflow
                return mid; 
            } else if ( x / mid < mid ) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
            
        }
        
        return -1;
    }
}

 

转载于:https://www.cnblogs.com/airwindow/p/4204966.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值