首页 > 其他 > 详细

LeetCode Search for Range

时间:2014-06-13 17:36:52      阅读:389      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
class Solution {
private:
    int getDirection(int A[], int idx, int target, bool isDefaultBack) {
        int r = A[idx] - target;
        if (r == 0) {
            r = isDefaultBack ? -1 : 1;
        }
        return r;
    }   
    int getFirstValueIndex(int A[], int n, int target, bool isFromBack) {
        int p = -1; 
        int q = n;
        while (p + 1 < q) {
            int mid_idx = (p + q) / 2;
            int where = getDirection(A, mid_idx, target, isFromBack);
            if (where < 0) {
                p = mid_idx;
            } else {
                q = mid_idx;
            }
        }
        if (p != -1 && A[p] != target) {
            p = -1; 
        }
        if (q == n || A[q] != target) {
            q = -1; 
        }
        return isFromBack ? p : q;
    }   
public:
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> res;
        res.push_back(getFirstValueIndex(A, n, target, false));
        res.push_back(getFirstValueIndex(A, n, target, true));
        return res;
    }   
};
bubuko.com,布布扣

进行两次二分查找,一次找upper bound一次找lower bound,如果线性查找的化就不符合要求了。

LeetCode Search for Range,布布扣,bubuko.com

LeetCode Search for Range

原文:http://www.cnblogs.com/lailailai/p/3784545.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!