程式語言 - LeetCode - C++ - 34. Find First and Last Position of Element in Sorted Array



參考資訊:
https://algo.monster/liteproblems/34
https://www.cnblogs.com/grandyang/p/4409379.html

題目:


解答:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        auto find_element = [&](int t) {
            int l = 0;
            int r = nums.size();

            while (l < r) {
                int m = l + ((r - l) / 2);

                if (nums[m] < t) {
                    l = m + 1;
                } else {
                    r = m;
                }
            }

            return r;
        };

        int st = find_element(target);
        if ((st == nums.size()) || (nums[st] != target)) {
            return { -1, -1 };
        }

        return { st, find_element(target + 1) - 1 };
    }
};