81. Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

---

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

 

posted @ 2013-09-16 10:20  LEDYC  阅读(154)  评论(0)    收藏  举报