其他分享
首页 > 其他分享> > 二分查找的左闭右开和左闭右闭写法中各种小细节深究

二分查找的左闭右开和左闭右闭写法中各种小细节深究

作者:互联网

写在前面

lower_bound查找的是升序序列中的第一个出现target的pos,区间应从右向左收缩。
upper_bound查找的是升序序列中的最后一个出现target的pos,区间应从左向右收缩。

主循环判断本质目的是为了确保整个区间能够被检索到。

1. 左闭右开

lower_bound

    int lower_bound(vector<int>& nums, int target){
        int left = 0, right = nums.size(), mid;
        while (left < right){
            mid = left + (right - left)/2;
            if (nums[mid] == target){
                right = mid;
            }else if (nums[mid] < target){
                left = mid + 1;
            }else if (nums[mid] > target){
                right = mid;
            }
        }
        // 边界
        if (left >= nums.size() || nums[left] != target) return -1;
        return left;
    }

注意

upper_bound

    int upper_bound(vector<int>& nums, int target){
        int left = 0, right = nums.size(), mid;
        while (left < right) {
            mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid;
            } else if (nums[mid] == target) {
                left = mid + 1;
            }
        }
        // 最后要检查  越界的情况
        if (left <= 0 || nums[left-1] != target)
            return -1;
        return left-1;
    }

2. 左闭右闭

lower_bound

int left_bound(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] < target) {
            left = mid + 1;
        } else if (nums[mid] > target) {
            right = mid - 1;
        } else if (nums[mid] == target) {
            // 别返回,锁定左侧边界
            right = mid - 1;
        }
    }
    // 最后要检查 left 越界的情况
    if (left >= nums.length || nums[left] != target)
        return -1;
    return left;
}

upper_bound

int right_bound(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] < target) {
            left = mid + 1;
        } else if (nums[mid] > target) {
            right = mid - 1;
        } else if (nums[mid] == target) {
            // 别返回,锁定右侧边界
            left = mid + 1;
        }
    }
    // 最后要检查 right 越界的情况
    if (right < 0 || nums[right] != target)
        return -1;
    return right;
}

当 target 比所有元素都小时,right 会被减到 -1,所以需要在最后防止越界.

标签:right,target,nums,int,mid,右闭,右开,左闭,left
来源: https://blog.csdn.net/allenhsu6/article/details/113779530