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

Have you met this question in a real interview?

Yes

Example

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

  1. binary search to find the left bound and right bound
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[] ans = new int[2];
        ans[0] = -1;
        ans[1] = -1;
        if (A == null || A.length == 0) {
            return ans;
        }


        //find first
        ans[0] = findFirst(A, target);
        if (ans[0] == -1) {
            return ans;
        }

        ans[1] = findLast(A, target);
        return ans;
    }

    public int findFirst(int[] A, int target) {
        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 if (A[mid] == target) {
                end = mid;
            } else {
                start = mid;
            }
        }

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

        return -1;
    }

    public int findLast(int[] A, int target) {
        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 if (A[mid] == target) {
                start = mid;
            } else {
                start = mid;
            }
        }

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

        return -1;
    }
}

results matching ""

    No results matching ""