首页 > 其他 > 详细

Search for a Range

时间:2015-11-28 11:58:55      阅读:359      评论:0      收藏:0      [点我收藏+]

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

如果不要求实现,用c++stl的lower_bound和upper_bound就可以了

class Solution {
public:
    int lower_bound(vector<int>& nums,int numsSize,int target)
    {
        int low = 0,high = numsSize;
        while(low<high){
            int mid = low+(high-low)/2;
            if(target <= nums[mid]){
                high = mid;
            }else{
                low = mid+1;
            }
        }
        return low;
    }
    int upper_bound(vector<int>& nums,int numsSize,int target)
    {
        int low = 0,high = numsSize;
        while(low<high){
            int mid = low+(high-low)/2;
            if(target < nums[mid]){
                high = mid;
            }else{
                low = mid+1;
            }
        }
        return low;
    }
    vector<int> searchRange(vector<int>& nums, int target) {
        int numsSize = nums.size();
        int low = lower_bound(nums,numsSize,target);
        vector<int> res;
        if(nums[low]!=target){
            res.push_back(-1);
            res.push_back(-1);
        }else{
            int high = upper_bound(nums,numsSize,target);
            res.push_back(low);
            res.push_back(high-1);
        }
        return res;
    }
};

 

Search for a Range

原文:http://www.cnblogs.com/zengzy/p/5002399.html

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