Search for a Range

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:
    vector<int> searchRange(int A[], int n, int target) 
    {
        int left=searchleft(A,0,n-1,target);
        int right=searchright(A,0,n-1,target);
        vector<int> v;
        v.push_back(left);
        v.push_back(right);
        return v;
    }
    int searchleft(int A[],int l,int r,int target)
    {
        if(l>r) return -1;
        int m=(l+r)/2;
        if(A[m]==target)
        {
            int index=searchleft(A,l,m-1,target);
            if(index==-1)   return m;
            else return index;
        }
        else if(A[m]>target) return searchleft(A,l,m-1,target);
        else return searchleft(A,m+1,r,target);
    }
    int searchright(int A[],int l,int r,int target)
    {
        if(l>r) return -1;
        int m=(l+r)/2;
        if(A[m]==target)
        {
            int index=searchright(A,m+1,r,target);
            if(index==-1)   return m;
            else return index;
        }
        else if(A[m]>target) return searchright(A,l,m-1,target);
        else return searchright(A,m+1,r,target);
    }
}; 
原文地址:https://www.cnblogs.com/erictanghu/p/3759326.html