2014年4月12日 星期六

[LeetCode] Search for a Range

Problem:
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].
Solution: O(logn)
public class Solution {
    public int[] searchRange(int[] A, int target) {
        int noResut[] = new int[]{-1,-1};
         if(A== null || A.length == 0){
            return noResut;
        }
        int index = getIndex(A,0,A.length-1,target);
        if(index == -1)
            return noResut;
        
        int start = index;
        int end = index;
        while(start >= 0 && A[start]== target ){
            start--;
        }
        while(end < A.length && A[end]== target ){
            end++;
        }
        return new int[]{start++,end--};
    }
    
    public int getIndex(int[] A, int start, int end,int target){
        if(start > end)
            return -1;
        int mid = (start+end)/2;
        if(A[mid] == target){
            return mid;
        }else if(A[mid] > target){
            return getIndex(A, start, mid-1, target);
        }else{
            return getIndex(A, mid+1, end, target);
        }
    }
}

沒有留言:

張貼留言