题目
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-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]
示例3:
输入:nums = [], target = 0
输出:[-1,-1]
解题思路
- 二分查找法,先查左边的索引,再查右边的索引
- 通过设置一个 bool 类型的变量,来区分左区间,还是右区间 3.在条件判断上,要注意返回的索引如果等于数组的长度是不行的,还得加上该索引下的值是否与 Target 相等 4.右区间的索引需要 -1
代码实现
class Solution {
int findExtremeInsertIndex(int[] nums, int target, boolean {
int lo = 0;
int hi = nums.length;
while(lo < hi){
int mid = (lo + hi) / 2;
if(nums[mid] > target || (left && target == nums[mid])){
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
public int[] searchRange(int[] nums, int target) {
int[] targetRange = {-1, -1};
// 寻找左边的索引
int lo = findExtremeInsertIndex(nums, target, true);
// 未找到与 target 相符的,返回 [-1,-1]
if(lo == nums.length || nums[lo] != target) {
return targetRange;
}
targetRange[0] = lo;
int hi = findExtremeInsertIndex(nums, target, false) - 1;
targetRange[1] = hi;
return
最后
- 时间复杂度: O(logn) ,其中 n 为数组的长度。二分查找的时间复杂度为 O(logn)
- 空间复杂度:O(1)
关注公众号---HelloWorld杰少