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

Solution: Find left bound and right bound by using Binary Search.

public int[] searchRange(int[] A, int target) {
    if(A == null || A.length == 0) {
        return new int[] {-1, -1};
    }
    int[] res = new int[2];
    boolean haveNum = false;
    int start = 0, end = A.length - 1;
    while(start <= end) {
        int mid = start + (end - start) / 2;
        if(A[mid] == target) {
            haveNum = true;
        }
        if(A[mid] < target) {
            start = mid + 1;
        }
        else {
            end = mid - 1;
        }
    }

    if(!haveNum) {
        return new int[]{-1, -1};
    }

    res[0] = start;

    int nstart = 0, nend = A.length - 1;
    while(nstart <= nend) {
        int mid = nstart + (nend - nstart) / 2;
        if(A[mid] <= target) {
            nstart = mid + 1;
        }
        else {
            nend = mid - 1;
        }
    }
    res[1] = nend;
    return res;
}

results matching ""

    No results matching ""