题目地址
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array
题目大意
https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
解题思路
利用二分查找
- 对nums进行二分查找到target的位置mid
- nums[low, mid - 1]内二分查找到第一个target的索引
- nums[mid + 1, high]内二分查找到最后一个target的索引
C++代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> pos = {-1, -1};
int low = 0, high = int(nums.size()) - 1;
while (low <= high) {
int mid = (high + low) / 2;
if (nums[mid] == target) {
// find start
pos = {mid, mid};
int tempLow = low;
int tempHigh = mid - 1;
while (tempLow <= tempHigh) {
int tempMid = (tempLow + tempHigh) / 2;
if (nums[tempMid] == target) {
pos[0] = tempMid;
tempHigh = tempMid - 1;
} else {
tempLow = tempMid + 1;
}
}
// find end
tempLow = mid + 1;
tempHigh = high;
while (tempLow <= tempHigh) {
int tempMid = (tempLow + tempHigh) / 2;
if (nums[tempMid] == target) {
pos[1] = tempMid;
tempLow = tempMid + 1;
} else {
tempHigh= tempMid - 1;
}
}
break;
}
if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return pos;
}
};