您的位置:首页 > 其它

leetcode旋转数组查找 二分查找的变形

2014-07-09 21:34 549 查看
http://blog.csdn.net/pickless/article/details/9191075

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e.,
0 1 2 4 5 6 7
might become
4 5 6 7 0 1 2
).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

设置 low=0 high=len-1

bsearch(A,low,high)=bsearch(A,low,mid-1)||bsearch(A,mid+1,high) (A[mid]!=target)

mid (A[mid]==target)

这是传统的思路:

我们经过观察发现,只要 A[high]>=A[low] 数组一定是递增的,则选用二分查找

如果不是,则分割 ,使用递归,一定能分割成数组满足第一种状态,

比如,上边的例子我们查找 5,

mid=3,A[mid]=7;分割成(4,5,6)和(0,1,2)连个尾巴都是大于首部,所以直接会被二分查找。

public class Solution {
public int search(int[] A, int target) {
int len=A.length;
if(len==0) return -1;
return    bsearch(A,target,0,len-1);

}

public int bsearch(int A[],int target,int low,int high)
{
if(low>high) return -1;
int idx=-1;
if(A[low]<=A[high]) //it must be YouXu,so binary search

{
while(low<=high)
{
int mid=(low+high)>>1;
if(A[mid]==target)
{
idx=mid;
return idx;
}
else if(A[mid]>target)
{
high=mid-1;
}
else low=mid+1;
}

}
else
{
int mid=(low+high)>>1;
if(A[mid]==target)
{
idx=mid;
return idx;

}
else
{
idx=bsearch(A,target,low,mid-1);
if(idx==-1)
{
idx=bsearch(A,target,mid+1,high);

}

}

}

return idx;

}
}


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