两次二分查找,第一次找low,第二次找high
[l,r)找high和(l,r]找low
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans;
if (nums.empty()) {
ans.push_back(-1), ans.push_back(-1);
return ans;
}
int l = -1, r = (int)nums.size()-1, low, high;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (nums[mid] < target) l = mid;
else r = mid - 1;
}
low = l + 1, l = 0, r = nums.size();
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] > target) r = mid;
else l = mid + 1;
}
high = r - 1;
if (low > high) ans.push_back(-1), ans.push_back(-1);
else ans.push_back(low), ans.push_back(high);
return ans;
}
};