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

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; }
}
上一篇:文件批量上传的工具,要实现暂停继续、断点续传等功能(使用QtNetwork和QHttpMultiPart,和定时器检查超时)


下一篇:UVA 11021 Tribles(递推+概率)