Search for a Range(lintcode 61)

Description

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

Interface

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
    }
}

Solution

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
        if (A == null || A.length == 0) {
            return new int[] {-1, -1};
        }

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

        while (start + 1 < end) {
            int mid = start + (end - start) / 2;

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

        int first = -1;

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

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

        while (start + 1 < end) {
            int mid = start + (end - start) / 2;

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

        int second = -1;

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

        return new int[]{first, second};
    }
}

results matching ""

    No results matching ""