The termination conditions about the binary search

About some thoughts of binary search:

To avoid some confusion of the binary search, like dead-loop or something.

Every time i write binary search, i always use the 'while' condition like this:

int l = 0;
int r = nums.size()-1;

while (l < r-1) {
// insert the specific code
} 


And then to check both the nums[l] and nums[r] with the final result.

This way could definitely eliminate the possibility of  dead-loop, like 'l' always be the 'mid', and 'mid' always equals to 'l'.

But this way is not very elegant, so, when could we use the condition like:

while (l<r) {
// insert the code here
}


To do like this way, we need have condition like:

while (l < r) {
            int mid = l + (r - l) / 2;
            if (citations[mid] >= size-mid) r = mid;
            else l = mid + 1; // The key
}


So if, l = mid + 1, then we could use while (l < r).

Like the following problem: https://leetcode.com/problems/h-index-ii/

Both solution can reach the correct answer:

// First Edition
class Solution {
public:
    int hIndex(vector<int>& citations) {
        if ((int)citations.size() == 0) return 0;
        int size = (int)citations.size();
        int l = 0;
        int r = size - 1;
        while (l < r-1) {
            int mid = l + (r - l) / 2;
            if (citations[mid] >= size-mid) r = mid;
            else l = mid + 1;
        }
        if (citations[l] >= size - l) return size-l;
        else if (citations[r] >= size - r) return size-r;
        return 0;
    }
};

// We can also write like this
class Solution {
public:
    int hIndex(vector<int>& citations) {
        if ((int)citations.size() == 0) return 0;
        int size = (int)citations.size();
        int l = 0;
        int r = size - 1;
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (citations[mid] >= size-mid) r = mid;
            else l = mid + 1;
        }
        if (citations[r] != 0)
            return size-r;
        return 0;
    }
};









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值