码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Search for Range

时间:2014-06-13 17:37:20      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

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

标签:style   class   blog   code   java   http   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!