Straightforward implementation in C++


  • 1
    F
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> retVal(2, -1);
        
        int L = 0, R = nums.size() -1;
        
        while (L <= R) {
            int mid = (L + R) / 2;
            if (nums[mid] == target) {
                retVal[0] = retVal[1] = mid;
                while (retVal[0] > 0 && nums[retVal[0] - 1] == target) retVal[0]--;
                while (retVal[1] < nums.size() - 1 && nums[retVal[1] + 1] == target) retVal[1]++;
                return retVal;
            } else if (target < nums[mid]) {
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }
        
        return retVal;
    }

  • 0
    A

    This solution does not meet the O(log n) requirement. It's O(n).


Log in to reply
 

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