32. Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

---

Basic idea is Binary search

-if left < target < mid, only need to search the left half

-if mid < target < right, only need to search the right half

- otherwise, need to search both sides

---

public class Solution {
    public int search(int[] A, int target) {       
        return helper(A, target, 0, A.length-1);        
    }
    
    public int helper(int[] A, int target, int l, int r){
        
        if(l <0 || r >= A.length || l > r)
            return -1;
            
        int mid = l + (r-l) / 2;
        
        if(A[mid] == target){
            return mid;
                    
        }else if(A[mid] > target && A[l] < target){
            // search left
            return helper(A, target, l, mid-1);
            
        }else if(A[mid] < target && target < A[r]){
            // search right
            return helper(A, target, mid+1, r);
            
        }else{
            // search both
            int rst;
            // left part
            rst = helper(A, target, l, mid-1);
            if(rst == -1)
                // right part
                rst = helper(A, target, mid+1, r);
            return rst;
            
        } 
    }
}

 

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