您的位置:首页 > 其它

LeetCode-Search in Rotated Sorted Array II

2015-01-20 07:13 148 查看
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:

public class Solution {
public boolean search(int[] A, int target) {
return searchRecur(A,target,0,A.length-1);
}

public boolean searchRecur(int[] A, int target, int start, int end){
if (start>end) return false;

int mid = (start+end)/2;
if (A[mid]==target) return true;

if (A[start]==A[mid] && A[end]==A[mid])
return ( searchRecur(A,target,start,mid-1) || searchRecur(A,target,mid+1,end) );

if (target>A[mid])
if (A[start]>A[mid] && target>=A[start])
return searchRecur(A,target,start,mid-1);
else return searchRecur(A,target,mid+1,end);
else
if (A[end]<A[mid] && target<=A[end])
return searchRecur(A,target,mid+1,end);
else return searchRecur(A,target,start,mid-1);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: