[leetcode刷题系列]Search for a Range

来源:互联网 发布:网络丑男 编辑:程序博客网 时间:2024/05/16 12:29

二分查找的基础题, 没啥好说的

class Solution {    // first place >= target    int binary(int *a, int st, int en, int target){        int low = st, high = en - 1, mid;        while(low <= high)            if(a[mid = low + high >> 1] >= target) high = mid - 1;else low = mid + 1;        return low;    }public:    vector<int> searchRange(int A[], int n, int target) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<int> vc;        int eq = binary(A, 0, n, target);        int bg = binary(A, 0, n, target + 1);        if(eq == bg){            vc.push_back(-1);            vc.push_back(-1);        }else{            vc.push_back(eq);            vc.push_back(bg - 1);        }        return vc;    }};


原创粉丝点击