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

public class Solution {
    public int[] searchRange(int[] A, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int start = 0;
        int end = A.length - 1;
        int l = -1;
        int r = -1;
        while(start <= end){
            int mid = (start + end) / 2;
            if(A[mid] == target) l = mid;
            /*如果是target <= A[mid] 找到的是数组下标最小的 */
            if(target <= A[mid]) end = mid - 1;
            else start = mid + 1;
        }
        /*不要忘记把指针归位*/
        start = 0;
        end = A.length - 1;
        while(start <= end){
            int mid = (start + end) / 2;
            if(A[mid] == target) r = mid;
            /*如果是target <= A[mid] 找到的是数组下标最大的 */
            if(target >= A[mid]) start = mid + 1;
            else end = mid - 1;
        }
        return new int[]{l, r};
    }
}
原文地址:https://www.cnblogs.com/RazerLu/p/3533071.html