Skip to content

二分查找的区间为何是 0 到 len(nums) 而不是 len(nums) #812

Open
@wangpeipei90

Description

@wangpeipei90

在使用二分查找来查找区间时,该题中h的初始值为何要设置为len(nums)?其他题中设置的均为len(nums)-1

    int l = 0, h = nums.length; // 注意 h 的初始值
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] >= target) {
            h = m;
        } else {
            l = m + 1;
        }
    }
    return l;
}

https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.md#6-%E6%9F%A5%E6%89%BE%E5%8C%BA%E9%97%B4

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions