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

leetcode[34]Search for a Range

时间:2015-02-10 15:04:55      阅读:150      评论: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].

class Solution {
public:
int find(int A[],int n, int target, int Left, int Right, int flag)
{
    if (A==NULL||n==0||Left>Right)return -1;
    int mid=(Left+Right)/2;
    if (A[mid]==target)
    {    
        int pos=flag?find(A,n,target,Left,mid-1,flag):find(A,n,target,mid+1,Right,flag);
        if(pos==-1)
            return mid;
        else 
            return pos;
    }
    else if (A[mid]>target)
    {
        find(A,n,target,Left,mid-1,flag);
    }
    else
    {
        find(A,n,target,mid+1,Right,flag);
    }
}
vector<int> searchRange(int A[], int n, int target) 
{
    vector<int> res;
    int lef=find(A,n,target,0,n-1,1);
    int rig=find(A,n,target,0,n-1,0);
    res.push_back(lef);
    res.push_back(rig);
    return res;
}
};

 

leetcode[34]Search for a Range

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283605.html

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