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/
利用二分查找
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;
}
};
34.find-first-and-last-position-of-element-in-sorted-array
原文:https://www.cnblogs.com/AndrewGhost/p/12310126.html