10/13/2012

Search for a Range


Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
Key: Binary search

public class Solution {
    public int[] searchRange(int[] A, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int left = getLeft(A, target);
        int right = getRight(A, target);
        return new int[]{left, right};
    }
    
    public int getLeft(int[] A, int target) {
        int start = 0;
        int end = A.length - 1;
        while (end >= start) {
            if (end == start) {
                if (A[start] == target) 
                    return start;
                else 
                    return -1;
            }
            
            int mid = (start + end) / 2;
            if (A[mid] > target) {
                end = mid - 1;
            }
            else if (A[mid] < target) {
                start = mid + 1;
            }
            else {
                end = mid;
            }
        }
        return -1;
    }
    
    public int getRight(int[] A, int target) {
        int start = 0;
        int end = A.length - 1;
        while (end >= start) {
            if (end == start) {
                if (A[start] == target) 
                    return start;
                else 
                    return -1;
            }
            
            int mid = (start + end) / 2;
            if (A[mid] > target) {
                end = mid - 1;
            }
            else if (A[mid] < target) {
                start = mid + 1;
            }
            else {
                if (end - start == 1) {
                    if (A[end] == target) {
                        return end;
                    }
                    else {
                        return start;
                    }
                }
                start = mid;
            }
        }
        return -1;
    }
}

No comments:

Post a Comment