1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Search for a Range

Posted on 2014-01-09 14:49  1957  阅读(148)  评论(0编辑  收藏  举报

裸的lower_bound, upper_bound的实现...还有点晕,等下看...

边界调来调去的过了...看来正确实现二分真不容易

 

class Solution {
public:
    int low(int A[] , int start , int end , int target) {
        int l = 0;
        int r = end;
        while(l < r){
            int mid = l  + (r-l)/2;
            if(A[mid] < target)  l = mid + 1;
            else r = mid;
        }
        return l;
    }
    int up(int A[] , int start , int end , int target) {
        int l = 0;
        int r = end;
        while(l < r){
            int mid = l + (r-l)/2;
            if(A[mid] <= target) l = mid + 1;
            else r = mid;
        }
        return l;
    }
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> ans;
        if(n <= 0) return ans;
        int l = low(A , 0 , n , target);
        int u = up(A , 0 , n , target);
       
         if(A[l] == target) {
             ans.push_back(l);
             ans.push_back(u-1);
         } else {
             ans.push_back(-1);
             ans.push_back(-1);
         }
         return ans;
    }
    
};