[leetcode刷题系列]Search for a Range

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

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;
    }
};


你可能感兴趣的:([leetcode刷题系列]Search for a Range)