class Solution {
public int[] searchRange(int[] nums, int target) {
int res1 = lowerbound(nums, target);
// 第一个大于target的下标,-1就是最后一次出现target的下标(前提是res1找到了)
int res2 = upperbound(nums, target) - 1;
if(res1 == nums.length || nums[res1] != target){
return new int[] {-1, -1};
}
return new int[] {res1, res2};
}
static int lowerbound(int[] nums, int target){
int begin = 0;
int end = nums.length - 1;
while(begin <= end){
int mid = (begin + end) / 2;
if(nums[mid] < target){
begin = mid + 1;
}else{
end = mid - 1;
}
}
return begin;
}
static int upperbound(int[] nums, int target){
int begin = 0;
int end = nums.length - 1;
while(begin <= end){
int mid = (begin + end) / 2;
if(nums[mid] > target){
end = mid - 1;
}else{
begin = mid + 1;
}
}
return begin;
}
}
【算法练习】LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置【lower bound和upper bound】
于 2022-01-15 16:52:32 首次发布