34. Search for a Range

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8

Output: [3,4]

提示:方法一:二分查找  右边界 通过 mid = (l+r +1)/2获得

           方法二:二分查找找到左边界,因为递增排序,所以右边界为target+1的左边界-1。注意target+1不存在时                              也要让l=mid +1。

答案:

class Solution {
private: 
    int left(vector<int>& nums, int target){
        int l = 0, r = nums.size();
        while(l < r){
            int mid = (l + r) / 2;
            if(nums[mid] < target)  l = mid + 1;
            else r = mid; 
        }
        return l;
    }
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if(nums.empty()) return {-1, -1};
        int l = left(nums, target);
        if(l == nums.size() || target != nums[l])  return {-1, -1};
        else return {l, left(nums, target + 1) - 1};
    }
};

利用STL:

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


vector<int> searchRange(vector<int>& nums, int target) {
    int lo = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
    if (lo == nums.size() || nums[lo] != target)
        return {-1, -1};
    int hi = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - 1;
    return {lo, hi};
}

猜你喜欢

转载自blog.csdn.net/qq_27012963/article/details/80046632