LeetCode-Search for a Range-搜索范围-二分查找

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

题目原意应该为使用二分搜索。搜lower_bound时直到a[l]=x时停止。搜upper_bound时直到a[r]=x时停止。

typedef pair<int,int> scpair;
class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
        auto l=lower_bound(A,A+n,target);
        auto r=upper_bound(A,A+n,target);
        vector <int> res(2);
        if (*l==target) res[0]=l-A;
        else res[0]=-1;
        if (*(r-1)==target) res[1]=r-A-1;
        else res[1]=-1;
        return res;
    }
};
View Code

 

posted @ 2014-10-13 11:09  zombies  阅读(128)  评论(0编辑  收藏  举报