Concise C++ Solution.


  • 0
    F

    Use a binary search as usual with an extra linear scan for the range when it finds the target.

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int left = 0, right = nums.size() - 1;
            while (left <= right) {
                int mid = left + (right - left)/2;
                if (nums[mid] == target) {
                    int j = mid, k = mid;
                    while (j>=0 && nums[j] == target) --j;
                    while (k<nums.size() && nums[k] == target) ++k;
                    return {j+1, k-1};
                }
                if (nums[mid] > target) right = mid-1;
                else left = mid+1;
            }
            return {-1, -1};
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.