在写这道题的时候,我发现我居然把二分的更新步骤搞错了,原来一直以为是left++;right–;,刚刚做题时发现是left = mid + 1; right = mid - 1;
搞清楚这个了之后,这道题就是一个很简单的二分了,找到target的索引之后往两边扩展即可。
class Solution {
private:
static int BinarySearch(int left, int right, vector<int>& nums, int target)
{
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result;
int l = nums.size();
int pos = BinarySearch(0, l - 1, nums, target);
if (pos == -1) {
result.push_back(-1);
result.push_back(-1);
return result;
}
int left = pos, right = pos;
while (left >= 0 && nums[left] == target) {
left--;
}
while (right < l && nums[right] == target) {
right++;
}
result.push_back(left + 1);
result.push_back(right - 1);
return result;
}
};