Search Insert Position

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 bsearch(int a[],int left,int right,int key){
        if(left>right)
            return left;
        int mid=left+(right-left)/2;
        if(a[mid]==key)
            return mid;
        else if(a[mid]<key)
            return bsearch(a,mid+1,right,key);
        else 
            return bsearch(a,left,mid-1,key);
    }

    int searchInsert(int A[], int n, int target) {
        return bsearch(A,0,n-1,target);
    }
};

 

posted @ 2014-11-06 15:03  li303491  阅读(98)  评论(0编辑  收藏  举报