lintcode-medium-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.

 

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[] res = new int[2];
        
        if(A == null || A.length == 0){
            res[0] = -1;
            res[1] = -1;
            return res;
        }
        
        int left = 0;
        int right = A.length - 1;
        
        while(left < right - 1){
            int mid = left + (right - left) / 2;
            
            if(A[mid] < target)
                left = mid + 1;
            else
                right = mid;
        }
        
        if(A[left] == target){
            res[0] = left;
        }
        else if(A[right] == target){
            res[0] = right;
        }
        else{
            res[0] = -1;
            res[1] = -1;
            return res;
        }
        
        left = 0;
        right = A.length - 1;
        
        while(left < right - 1){
            int mid = left + (right - left) / 2;
            
            if(A[mid] > target)
                right = mid - 1;
            else
                left = mid;
        }
        
        if(A[right] == target)
            res[1] = right;
        else
            res[1] = left;
        
        return res;
    }
}

 

posted @ 2016-04-05 17:11  哥布林工程师  阅读(139)  评论(0编辑  收藏  举报