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

leetcode:Search for a Range

时间:2014-12-28 22:09:56      阅读:193      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!