2014年5月11日星期日

Binary Search Solution - Search in Rotated Sorted Array ***

The idea is to implement Binary Search, notice that to add if end-start<2 to catch the target is NOT in array case, and for binary part, compare middle with start, and two cases need to call both left and right, versus the other two only call one side!!! For two sides cases, add * -1 to make the result correctly.

public class Solution {
    public int search(int[] A, int target) {
        if(A==null || A.length == 0){
            return -1;
        }
        return searchOps(A, target, 0, A.length-1);
    }
   
    private int searchOps(int[] A, int target, int start, int end){
        if(target == A[start]){
            return start;
        }
        if(target == A[end]){
            return end;
        }
        if(end - start < 2){ //case for not Found!!!
            return -1;
        }
        int midIndex = (start + end) / 2;
        if(A[midIndex] == target){
            return midIndex;
        }
        if(target > A[start] && A[midIndex] < A[start]){
            return searchOps(A, target, start, midIndex - 1);
        }else if(target > A[start] && A[midIndex] > A[start]){
            return searchOps(A, target, start, midIndex - 1) * (-1) * searchOps(A, target, midIndex + 1, end);
        }else if(target < A[start] && A[midIndex] > A[start]){
            return searchOps(A, target, midIndex + 1, end);
        }else if(target < A[start] && A[midIndex] < A[start]){
            return searchOps(A, target, start, midIndex - 1) * (-1) * searchOps(A, target, midIndex + 1, end);
        }
        return -1;
    }
}

没有评论: