【二分算法】

2023-12-15 08:11:40

适用范围

有序的数据结构

选定区间

① [left, right]左闭右闭

right = numsize - 1
这种情况下,left = right是有意义的,故while(left <= right)

当nums[mid] > target时,right = mid - 1
当nums[mid] < target时,left = mid + 1

因为确定nums[mid]不是tartget

② [left, right)左闭右开

right = numsize
这种情况下,left = right没有意义,故while(left < right)
当nums[mid] > target时,right = mid
当nums[mid] < target时,left = mid + 1 注意此处还是mid+1,因为左边还是闭
因为是在左闭右开的区间中找,如果right = mid - 1,那就相当于把num[mid - 1]去掉了

最后附上C语言代码

// 左闭右闭
int search(int* nums, int numsSize, int target) {
    int left = 0;
    int right = numsSize - 1; // 此处为数组最大值的下标
    int mid = 0;

    while (left <= right)
    {
        mid = left + (right - left) / 2;
        if (nums[mid] == target)
            return mid;
        else if (nums[mid] > target)
            right = mid - 1;
        else if (nums[mid] < target)
            left = mid + 1;
    }
    return -1;
}
//左闭右开
int search(int* nums, int numsSize, int target) {
    int left = 0;
    int right = numsSize; // 此处为数组大小
    int mid = 0;

    while (left < right)
    {
        mid = left + (right - left) / 2;
        if (nums[mid] == target)
            return mid;
        else if (nums[mid] > target)
            right = mid;
        else if (nums[mid] < target)
            left = mid + 1; // 因为是左闭,还是mid + 1
    }
    return -1;
}

文章来源:https://blog.csdn.net/Mr_robot714/article/details/134988964
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。