leetcode@ [34] Search for a Range (STL Binary Search)

https://leetcode.com/problems/search-for-a-range/

Given a sorted array of integers, 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

明显的,这道题需要二分查找。实际上STL上已经为我们实现好了 二分查找 函数的接口。对于“vector”容器,我们可以利用“lower_bound” 查找 目标数值 target 第一次出现的位置。如果原数组中并不存在这个 target,lower_bound会返回第一个比target值大的位置。利用lower_bound函数获取 target 在原数组的位置:auto p = lower_bound(vec.begin(), vec.end(), target);而类似的函数upper_bound则会返回第一个比target大的位置。注意:auto p 在这里是vector 迭代器类型,转换成数字下表为 idx = p - vec.begin();

代码如下:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        auto p1 = lower_bound(nums.begin(), nums.end(), target);
        
        auto p2 = upper_bound(nums.begin(), nums.end(), target);
        
        vector<int> res; res.clear();
        if(*p1 != target) {
            res.push_back(-1);
            res.push_back(-1);
            return res;
        }
        
        res.push_back(p1 - nums.begin());
        res.push_back(p2 - nums.begin() - 1);
        
        return res;
    }
};
View Code
原文地址:https://www.cnblogs.com/fu11211129/p/5096959.html