【LeetCode】34. 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,找不到则返回默认的ret值[-1, -1]

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

具体来说,ret[0]不断向左扩展,ret[1]不断向右扩展。

class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> ret(2, -1);
        int left;
        int right;
        int low = 0;
        int high = n-1;
        while((left = binarySearch(A, low, high, target)) != -1)
        {
            ret[0] = left;
            high = left-1;
        }
        low = 0;
        high = n-1;
        while((right = binarySearch(A, low, high, target)) != -1)
        {
            ret[1] = right;
            low = right+1;
        }
        return ret;
    }
    int binarySearch(int A[], int left, int right, int target)
    {
        while(left <= right)
        {
            int mid = left + (right-left) / 2;
            if(A[mid] == target)
                return mid;
            else if(A[mid] < target)
                left = mid + 1;
            else
                right = mid - 1;
        }
        return -1;
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4170659.html