Given a sorted array of n integers, find the starting and ending position of a given target value. If the target is not found in the array, return [-1, -1].

Example Example 1: Input: [] 9 Output: [-1,-1]

Example 2: Input: [5, 7, 7, 8, 8, 10] 8 Output: [3, 4] Challenge O(log n) time.

public class Solution {
    /**
     * @param A: an integer sorted array
     * @param target: an integer to be inserted
     * @return: a list of length 2, [index1, index2]
     */
    public int[] searchRange(int[] A, int target) {
        // write your code here
        int[] res = {-1, -1};
        if(A == null || A.length == 0) return res;

        int start = 0;
        int end = A.length - 1;
        while(start + 1 < end) {
            int middle = start + (end - start) / 2;
            if(A[middle] < target) start = middle;
            else if(A[middle] >= target) end = middle;
        }
        if(A[start] == target) res[0] = start;
        else if(A[end] == target) res[0] = end;

        start = 0;
        end = A.length - 1;

        while(start + 1 < end) {
            int middle = start + (end - start) / 2;
            if(A[middle] <= target) start = middle;
            else if(A[middle] > target) end = middle;
        }
        if(A[end] == target) res[1] = end;
        else if(A[start] == target)  res[1] = start;

        return res;
    }
}

results matching ""

    No results matching ""