【题解】
二分某个数的上下界。 其实这个方法并不难。 只要你想清楚了二分最后一次执行的位置在什么地方就不难了。【代码】
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans;ans.clear();
int len = nums.size();
int l = 0,r = len-1;
while (l<=r){
int mid = (l+r)/2;
if (target<=nums[mid]){
r = mid-1;
}else{
l = mid+1;
}
}
if (r+1<=len-1 && nums[r+1]==target){
ans.push_back(r+1);
}else{
ans.push_back(-1);ans.push_back(-1);
return ans;
}
l = 0,r = len-1;
while (l<=r){
int mid = (l+r)/2;
if (target>=nums[mid]){
l = mid+1;
}else{
r = mid-1;
}
}
ans.push_back(l-1);
return ans;
}
};