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

Challenge:

O(log n) time.

Solution:

This is a combination problem of First Position of Target and Last Position of Target. We find the first position and then find the last position.

Code:

public int[] searchRange(int[] nums, int target) {
    if (nums == null || nums.length == 0) {
        return new int[] {-1, -1};
    }
    int start = 0;
    int end = nums.length - 1;
    return new int[] {findFirst(nums, target, start, end),
                        findLast(nums, target, start, end)};
}
private int findFirst(int[] nums, int target, int start, int end) {
    if (start + 1 >= end) {
        if (nums[start] == target) {
            return start;
        }
        if (nums[end] == target) {
            return end;
        }
        return -1;
    } else {
        int mid = start + (end - start) / 2;
        if (nums[mid] < target) {
            start = mid;
        } else {
            end = mid;
        }
        return findFirst(nums, target, start, end);
    }
}
private int findLast(int[] nums, int target, int start, int end) {
    if (start + 1 >= end) {
        if (nums[end] == target) {
            return end;
        }
        if (nums[start] == target) {
            return start;
        }
        return -1;
    } else {
        int mid = start + (end - start) / 2;
        if (nums[mid] <= target) {
            start = mid;
        } else {
            end = mid;
        }
        return findLast(nums, target, start, end);
    }
}

results matching ""

    No results matching ""