题干:
https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
我们可以使用C++的二分查找。
有轮子不用是傻子 ^ _ ^,哈哈哈。当然,以咱们的实力,你觉得咱们会写不出来自己的算法吗?咱们只是经过深思熟虑后,决定把时间用在刀刃上。(ps:Where is your face?)
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.empty()) return vector<int>{-1, -1};
auto left = lower_bound(nums.begin(), nums.end(), target);//左区间
auto right = upper_bound(nums.begin(), nums.end(), target);//右区间
//让我们祈祷编译器让left不越界,希望它会偷懒。如果left == end(),祈祷编译器会直接跳过*left所在表达式
if (left == nums.end() || *left != target) { return vector<int>{-1, -1}; }//数组没有target
else {
return vector<int>{static_cast<int>(left - nums.begin()), static_cast<int>(right - nums.begin() - 1) };
}
}
};