https://leetcode.cn/circle/discuss/SqopEo/

关键

其实只需要调用std的函数库即可

本质上只是下面注释的那几行

        auto low = std::lower_bound(nums.begin(), nums.end(), target); // 元素=>target
        auto up = std::upper_bound(nums.begin(), nums.end(), target);  // 元素>target

例题

https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/

这个需要将迭代器转换为索引

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        std::vector<int> loc(2, -1);
        auto low = std::lower_bound(nums.begin(), nums.end(), target); // <=
        auto up = std::upper_bound(nums.begin(), nums.end(), target);  // >
        if (low != nums.end() && *low == target) {
            // 将迭代器转换为索引
            loc[0] = low - nums.begin();
            loc[1] = up - nums.begin() - 1;
        }
        return loc;
    }
};

Hey!

If you have any non-algorithmic questions about the code, send me a message and I will be happy to help. I also hope to make more like-minded friends.