跳转至

34.在排序数组中查找元素的第一个和最后一个位置

题目描述

原题

给定一个按照升序排列的整数数组nums,和一个目标值target。找出给定目标值在数组中的开始位置和结束位置。

你的算法时间复杂度必须是 O\(log n\) 级别。

如果数组中不存在目标值,返回 [-1, -1]

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]

示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]

题解

用二分查找找到目标数的左边界和有边界

public int[] searchRange(int[] nums, int target) {
    return new int[]{left_bound(nums,target),right_bound(nums,target)};
}
public int left_bound(int[] nums, int target) {
    int low = 0, high = nums.length - 1;
    while (low <= high) {
        int middle = low + (high - low) / 2;
        if (nums[middle] > target) {
            high = middle - 1;
        } else if (nums[middle] < target) {
            low = middle + 1;
        } else {
            high = middle - 1;
        }
    }
    //检查出界情况
    if (low > nums.length -1 || nums[low] != target) {
        return -1;
    }
    return low;
}
public int right_bound(int[] nums, int target) {
    int low = 0, high = nums.length - 1;
    while (low <= high) {
        int middle = low + (high - low) / 2;
        if (nums[middle] > target) {
            high = middle - 1;
        } else if (nums[middle] < target) {
            low = middle + 1;
        } else {
            low = middle + 1;
        }
    }
    if(high < 0 || nums[low]!=target){
        return -1;
    }
    return high;
}