首页 > 其他 > 详细

leetcode:Search for a Range

时间:2014-12-28 22:08:49      阅读:289      评论: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].

 

大致题意:找到值为target的下标范围

vector<int> searchRange(int A[], int n, int target) {
    int l,r,mid;
    std::vector<int> ans;
    l=0;
    r=n-1;
    //找到第一个不小于target的位置
    while (l<=r)
    {
        mid=(l+r)>>1;
        if (A[mid]>=target)
            r=mid-1;
        else l=mid+1;
    }
    if (A[l]==target)
        ans.push_back(l);
    else{
        ans.push_back(-1);
        ans.push_back(-1);
        return ans;
    }
    l=0;
    r=n-1;
    //找到第一个大于target的位置
    while (l<=r)
    {
        mid=(l+r)>>1;
        if (A[mid]>target)
            r=mid-1;
        else l=mid+1;
    }
    ans.push_back(l-1);
    return ans;
}

leetcode:Search for a Range

原文:http://www.cnblogs.com/mintmy/p/4190597.html

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