C++ cheating with equal_range function


  • -1
    W
    vector<int> searchRange(vector<int>& nums, int target) 
    {
        vector<int> range;
        auto equalRange = equal_range(nums.begin(), nums.end(), target);
        if (equalRange.first == equalRange.second)
        {
        	range.push_back(-1);
        	range.push_back(-1);
        }
        else
        {
            range.push_back(equalRange.first - nums.begin());
            range.push_back(equalRange.second - nums.begin() - 1);
        }
        return range;
    }

  • 0

    Just a bit shorter:

    vector<int> searchRange(vector<int>& nums, int target) {
        auto equalRange = equal_range(nums.begin(), nums.end(), target);
        if (equalRange.first == equalRange.second)
            return {-1, -1};
        return {equalRange.first - nums.begin(),
                equalRange.second - nums.begin() - 1};
    }
    

    Or:

    vector<int> searchRange(vector<int>& nums, int target) {
        auto equalRange = equal_range(nums.begin(), nums.end(), target);
        int start = equalRange.first - nums.begin();
        int end = equalRange.second - nums.begin() - 1;
        if (start > end)
            return {-1, -1};
        return {start, end};
    }

Log in to reply
 

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