Ceiling and floor of one array and target

下面介绍两个子问题。

给定一个 nums[]. target, 求 该数组中,大于等于target的最小值的index

private int ceil(int[] nums, int target) {
    int begin = 0;
    int end = nums.length - 1;
    while (begin <= end) {
        int mid = begin + (end - begin) / 2;
        if (nums[mid] > target) {
            end = mid - 1;
        }
        else if (nums[mid] < target) {
            begin = mid + 1;
        }
        else {
            return mid;
        }
    }

    return begin;
}

求小于等于target 的最大数的index

private int floor(int[] nums, int target) {
    int begin = 0;
    int end = nums.length - 1;
    while (begin <= end) {
        int mid = begin + (end - begin) / 2;
        if (nums[mid] > target) {
            end = mid - 1;
        }
        else if (nums[mid] < target) {
            begin = mid + 1;
        }
        else {
            return mid;
        }
    }
    return end;
}

感觉会经常用,记住了。

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/6f40fff46493#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞