leetcode之Search for a Range

来源:互联网 发布:python 3.4.3.msi 编辑:程序博客网 时间:2024/04/29 20:06
class Solution {
public:
    int bsearch(int A[], int beg, int end, int target) {
        if (beg>end) {
            return -1;
        }
        int mid = (beg+end)/2;
        if (A[mid]==target) {
            return mid;
        } else if (A[mid]<target) {
            return bsearch(A, mid+1, end, target);
        } else {
            return bsearch(A, beg, mid-1, target);
        }
    }
    vector<int> searchRange(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> res;
        int index = bsearch(A, 0, n-1, target);
        if (index==-1) {
            res.push_back(-1);
            res.push_back(-1);
            return res;
        } else {
            int i = index-1;
            /*if (index==0) {
                res.push_back(index);
            }*/
            while (i>=0&&A[i]==target) {
                    i--;
            }
            res.push_back(i+1);
            i=index+1;
            while (i<n&&A[i]==target) {
                    i++;
            }
            res.push_back(i-1);
        }
        return res;
    }
};
原创粉丝点击