Search for a Range

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:

Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].

Notes:

  1. Binary search find left and then find right
    public int[] searchRange(int[] A, int target) {
        if (A == null || A.length == 0) {
            return new int[]{-1, -1};
        }

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

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

        if (A[start] == target) {
            left = start;
        } else if (A[end] == target) {
            left = end;
        }

        if (left == -1) {
            return new int[]{-1, -1};
        }

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

        if (A[end] == target) {
            right = end;
        } else if (A[start] == target) {
            right = start;
        }

        return new int[]{left, right};
    }

results matching ""

    No results matching ""