LeetCode-Search in Rotated Sorted Array II

LiBlog發表於2015-01-20

Analysis:

For target>A[mid]:

There is only one case that we should seach [start,mid-1]: Peak is in the left, i.e., A[start]>A[mid] && target>=A[start].

For target<A[mid]:

There is only one case that we should search [mid+1,end]: Peak is in the right, i.e., A[end]<A[mid] && target<=A[end].

 

Solution:

 1 public class Solution {
 2     public boolean search(int[] A, int target) {
 3         return searchRecur(A,target,0,A.length-1);
 4     }
 5     
 6     public boolean searchRecur(int[] A, int target, int start, int end){
 7         if (start>end) return false;
 8         
 9         int mid = (start+end)/2;
10         if (A[mid]==target) return true;
11         
12         if (A[start]==A[mid] && A[end]==A[mid])
13             return ( searchRecur(A,target,start,mid-1) || searchRecur(A,target,mid+1,end) );
14         
15         if (target>A[mid])
16             if (A[start]>A[mid] && target>=A[start]) 
17                 return searchRecur(A,target,start,mid-1);
18             else return searchRecur(A,target,mid+1,end);
19         else 
20             if (A[end]<A[mid] && target<=A[end])
21                 return searchRecur(A,target,mid+1,end);
22             else return searchRecur(A,target,start,mid-1);
23         
24     }
25         
26         
27 }

 

相關文章