34. Search for a Range

Given an array of integers 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].

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

 

其实题意是想让自己写的二分,但是我想练习一下stl的二分的函数

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> ans;
        if(lower_bound(nums.begin(),nums.end(),target) == nums.end()||*(lower_bound(nums.begin(),nums.end(),target)) != target)
        {
            ans.push_back(-1);
            ans.push_back(-1);
            return ans;
        }
        int k1 = lower_bound(nums.begin(),nums.end(),target) - nums.begin();
        int k2 = upper_bound(nums.begin(),nums.end(),target) - nums.begin() -1;
        
        ans.push_back(k1);
        ans.push_back(k2);
        return ans;
    }
};
posted @ 2017-07-11 00:06  可达龙  阅读(139)  评论(0编辑  收藏  举报