33. 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 {
    public int[] searchRange(int[] A, int target) {
        
        return helper(A, target, 0, A.length-1);
    
    }
    
    
    private int[] helper(int[] A, int target, int l, int r){
        
        // not found
        if(l <0 || r >= A.length || l > r){        
            int[] rst = {-1, -1};
            return rst;
        }
        
            
        // bst 
        int mid = l + (r-l) / 2;
       
        if(A[mid] == target){
                       
            // found, search for range
            int[] rst = new int[2];
            int x = mid, y = mid;
            
            while(x>=0 && A[x]==target)
                x--;
            
            while(y<A.length && A[y]==target)
                y++;
        
            rst[0] = x+1;
            rst[1] = y-1;
            
            return rst;
                    
        }else if(A[mid] > target){
            // search left
            return helper(A, target, l, mid-1);
            
        }else{
            // search right
            return helper(A, target, mid+1, r);        
        }
    }
}

 

posted @ 2013-09-04 09:39  LEDYC  阅读(152)  评论(0)    收藏  举报