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

思路:二分查找法,找到目标值的范围,时间复杂度在O(logn)。先找出左边第一个等于目标值的位置,再找出右边最后一个等于目标值的位置,然后返回这个范围。

class Solution {
public:
    int findleft(int A[],int n,int target)
    {
        if(n==0)
            return -1;
        int left=0;
        int right=n-1;
        while(left<right)
        {
            int mid=(left+right)>>1;
            if(A[mid]>=target)
                right=mid;
            else
                left=mid+1;
        }
        if(target==A[left])
            return left;
        else
            return -1;
    }
    int findright(int A[],int n,int target)
    {
        if(n==0)
            return -1;
        int left=0;
        int right=n-1;
        while(left<=right)
        {
            int mid=(left+right)>>1;
            if(A[mid]>target)
                right=mid-1;
            else
                left=mid+1;
        }
        if(A[right]==target)
            return right;
        else 
            return -1;
    }
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> result(2);
        result.clear();
        for(int i=0;i<2;i++)
            result.push_back(-1);
        int left=findleft(A,n,target);
        int right=findright(A,n,target);
        result[0]=left;
        result[1]=right;
        return result;
    }
};

 

posted @ 2014-04-19 11:34  Awy  阅读(169)  评论(0编辑  收藏  举报