Tuesday, July 22, 2014

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

就是两次二分找两次边界
public class Solution {
    //Time: O(logn)  Space: O(1)
    public int[] searchRange(int[] A, int target) {
        int[] res = new int[2];
        res[0] = res[1] = -1;
        if (A == null || A.length == 0) {
            return res;
        }
        
        int left = 0;
        int right = A.length - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (target <= A[mid]) {
                right = mid;
            } else {
                left = mid;
            }
        }
        if (A[left] == target) {
            res[0] = left;
        } else if (A[right] == target) {
            res[0] = right;
        }
        
        left = 0;
        right = A.length - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (target < A[mid]) {
                right = mid;
            } else {
                left = mid;
            }
        }
        if (A[right] == target) {
            res[1] = right;
        } else if (A[left] == target) {
            res[1] = left;
        }
        return res;
    }
}

No comments:

Post a Comment