这题还蛮有意思的,看了下解析,分成两部分分开来求解。
左右边界都是普通的二分查找算法,重点就是当等于的时候的处理,左边界函数等于目标值的时候,要记录当前mid的值作为边界,同时区间要向左移。
反过来,右边界的话,区间要向右移动。记得记录相等时候的mid值,最后一次相等记录的值也就是这个边界值。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
return {getLeftBorder(nums, target), getRightBorder(nums, target)};
}
private:
int getRightBorder(const vector<int>& nums, int target){
int head = 0, tail = nums.size() - 1;
int rightBorder = -1;
while(head <= tail){
int mid = head + (tail - head) / 2;
if(nums[mid] < target){
head = mid + 1;
}else if(nums[mid] > target){
tail = mid - 1;
}else{
rightBorder = mid;
head = mid + 1;
}
}
return rightBorder;
}
int getLeftBorder(const vector<int>& nums, int target){
int head = 0, tail = nums.size() - 1;
int leftBorder = -1;
while(head <= tail){
int mid = head + (tail - head) / 2;
if(nums[mid] == target){
leftBorder = mid;
tail = mid - 1;
}else if(nums[mid] > target){
tail = mid -1;
}else{
head = mid + 1;
}
}
return leftBorder;
}
};
标签:head,target,nums,int,mid,34,tail,查找,排序
From: https://www.cnblogs.com/llllmz/p/18397031