首页 > 代码库 > 【LeetCode】Search for a Range

【LeetCode】Search for a Range

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)时间要求,显然用二分查找。

思路是先用二分查找找到其中一个target,找不到则返回[-1, -1]

找到之后从这个位置往两边递归进行二分查找进行范围的拓展。

部分参考了xiao.he.587的思路。

class Solution {public:    vector<int> searchRange(int A[], int n, int target) {        vector<int> ret(2, -1);        int ind = Helper(A, 0, n-1, target);        if(ind != -1)        {//find one target            int left = ind;            int right = ind;            ret[0] = left;            ret[1] = right;            //recursively extend left towards 0            while((left = Helper(A, 0, left-1, target)) != -1)                ret[0] = left;            //recursively extend right towards n-1            while((right = Helper(A, right+1, n-1, target)) != -1)                ret[1] = right;        }        return ret;    }    int Helper(int A[], int low, int high, int target)    {//binary search        while(low <= high)        {            int mid = low + (high-low)/2;            if(A[mid] == target)                return mid;            else if(A[mid] > target)                high = mid-1;            else                low = mid+1;        }        return -1;    }};

【LeetCode】Search for a Range