二分查找排序数组中指定数所在区间

import java.util.Arrays;

public class Solution {
    //解法1
    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0)
            return new int[]{-1, -1};
        int i = 0;
        int j = nums.length - 1;
        int start = -1, end = -1;
        int mid;
        while (i < j) {
            mid = (i + j) / 2;
            if (target <= nums[mid]) {
                j = mid;
            } else {
                i = mid + 1;
            }
        }
        if (nums[i] == target) {
            start = i;
        } else {
            return new int[]{-1, -1};
        }

        j = nums.length - 1;
        while (i < j) {
            mid = (i + j + 1) / 2;
            if (target >= nums[mid]) {
                i = mid;
            } else {
                j = mid - 1;
            }
        }
        if (nums[i] == target) {
            end = i;
        }

        return new int[]{start, end};
    }

    //解法2
    public int[] searchRange2(int[] nums, int target) {
        if (nums == null || nums.length == 0)
            return new int[]{-1, -1};
        int start = lowerBound(nums, target);
        if (start >= 0 && start < nums.length && nums[start] == target)
            return new int[]{start, lowerBound(nums, target + 1) - 1};
        return new int[]{-1, -1};
    }

    public int lowerBound(int[] nums, int target) {
        int i = 0;
        int j = nums.length;
        int mid;
        while (i < j) {
            mid = (i + j) / 2;
            if (target <= nums[mid]) {
                j = mid;
            } else {
                i = mid + 1;
            }
        }
        return i;
    }

    public static void main(String[] args) {
        int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 8;
        System.out.println(Arrays.toString(new Solution().searchRange(nums, target)));
    }

}

[参考]
https://discuss.leetcode.com/topic/5891/clean-iterative-solution-with-two-binary-searches-with-explanation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值