您的位置:首页 > 其它

【LeetCode】Search in Rotated Sorted Array II

2014-12-15 12:52 393 查看
public class Solution {
public boolean binarySearch0(int[] num, int l, int h, int target){
while(l <= h){
int mid = l + (( h - l) >> 1);
if(num[mid] > target) h = mid - 1;
else if(num[mid] < target) l = mid + 1;
else return true;
}
return false;
}
public boolean binarySearch(int[] num, int start, int end, int target){
if(num[start] < num[end]) return binarySearch0(num, start, end, target);//注意此处不能有等号
if(start > end) return false;
if(start == end){
if(num[start] == target) return true;
else return false;
}
if(start + 1 == end){
if(num[start] == target || num[end] == target ) return true;
else return false;
}
int mid = start + ((end - start) >> 1);
if(num[mid] == target) return true;
return (binarySearch(num, start, mid - 1, target) || binarySearch(num, mid + 1, end, target));//分治的思想同时写好递归的出口
}
public boolean search(int[] A, int target) {
return binarySearch(A, 0 ,A.length - 1, target);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: