Search for a Range

来源:互联网 发布:上海软件研发质量咨询 编辑:程序博客网 时间:2024/06/05 01:58

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

二分查找,找到target后,再往两侧查找直到A[i]不等于target。

vector<int> searchRange(int A[], int n, int target){    int left = 0, right = n - 1, mid;    vector<int> ans(2);    while(left <= right)    {        mid = (left + right) / 2;        if(target == A[mid])        {            int leftPos = mid;            while(leftPos >= left && A[leftPos] == target)                leftPos--;            ans[0]=leftPos+1;            int rightPos = mid;            while(rightPos <= right && A[rightPos] == target)                rightPos++;            ans[1]=rightPos-1;            return ans;        }        else if(target < A[mid])          right = mid - 1;        else          left = mid + 1;    }    ans[0]=-1;    ans[1]=-1;    return ans;}



0 0
原创粉丝点击