leetcode -- Search for a Range

来源:互联网 发布:淘宝充话费怎么代理 编辑:程序博客网 时间:2024/06/06 08:30

Q: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].

分析:因为是有顺序序列,应该可以通过二分法查找.两个递归出口:(1)n=1且没有目标找到;(2)已经找到目标.
需要注意的是target>A[n/2]的情况,这时对[A+n/2, n-n/2]子序列重新递归查找,返回值target位置要加上之前的n/2.

class Solution {public:    vector<int> searchRange(int A[], int n, int target) {        vector<int> ret;        if(n == 1 && target !=A[0])   //递归出口1,找不到目标值            ret.assign(2, -1);        else if(target == A[n/2]){      //递归出口2,找到目标值            int tbeg = n/2, tend = n/2;            while((--tbeg) >= 0 && target == A[tbeg]);            while((++tend) < n && target == A[tend]);            ret.push_back(tbeg + 1);            ret.push_back(tend - 1);        }        else if(target < A[n/2])            ret = searchRange(A, n/2, target);        else{    ret = searchRange(A + n/2, n - n/2, target);    if(ret[0] == -1 && ret[1] == -1)  return ret;    ret[0] += n/2; ret[1] += n/2;       //***attention***        }        return ret;    }};


0 0