My C++ solution with two binary searches, 13ms


  • 0
    W

    class Solution {
    public:
    vector<int> searchRange(vector<int>& nums, int target) {
    int low = 0, high = nums.size() - 1;
    vector<int> res(2, -1);

        while(low < high)
        {
            int mid = (low + high) / 2;  // get the mid by abandoning the decimal part
            
            if(nums[mid] == target)
                high = mid;
            else if(nums[mid] > target)
                high = mid -1;
            else
                low = mid + 1;
        }
        
        if(nums[high] == target)
            res[0] = high;
            
        low = 0;
        high = nums.size() - 1;
        while(low < high)
        {
            int mid = (low + high) / 2;    // get the mid by add the decimal part
            if( mid * 2 != (low + high) )
                mid += 1;
            
            if(nums[mid] == target)
                low = mid;
            else if(nums[mid] > target)
                high = mid -1;
            else
                low = mid + 1;
        }
        
        if(nums[low] == target)
            res[1] = low;
            
        return res;
    }
    

    };


Log in to reply
 

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