码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Search in Rotated Sorted Array II

时间:2015-01-20 07:49:37      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

LeetCode-Search in Rotated Sorted Array II

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4235147.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!