34 - Find First and Last Position of Element in Sorted Array

 C++

  • class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int l = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
            int r = lower_bound(nums.begin(), nums.end(), target + 1) - nums.begin();
            if (l == r) return {-1, -1};
            return {l, r - 1};
        }
    };
JS
var searchRange = function (nums, target) {
    function search(x) {
        let left = 0,
            right = nums.length;
        while (left < right) {
            const mid = (left + right) >> 1;
            if (nums[mid] >= x) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
    const l = search(target);
    const r = search(target + 1);
    return l == r ? [-1, -1] : [l, r - 1];
};

Comments