题目链接:34. 在排序数组中查找元素的第一个和最后一个位置 - 力扣(LeetCode)
先用二分找到元素的位置,然后往前找第一次出现的位置,往后找最后一次出现的位置
代码语言:javascript复制class Solution {
public:
vector<int> searchRange(vector<int> &nums, int target) {
int begin = -1, end = -1, left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = (left right) / 2;
if (nums[mid] == target) {
begin = end = mid;
while (mid && nums[--mid] == target)--begin;
mid = (left right) / 2;
while ( mid < nums.size() && nums[mid] == target) end;
return {begin, end};
}
if (nums[mid] < target)
left = mid 1;
else
right = mid - 1;
}
return {-1, -1};
}
};