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)连个尾巴都是大于首部,所以直接会被二分查找。

 

 1 public class Solution {

 2     public int search(int[] A, int target) {

 3         int len=A.length;

 4         if(len==0) return -1;

 5     return    bsearch(A,target,0,len-1);

 6         

 7         

 8         

 9     }

10     

11     public int bsearch(int A[],int target,int low,int high)

12     {

13         if(low>high) return -1;   

14         int idx=-1;

15         if(A[low]<=A[high]) //it must be YouXu,so binary search

16         

17         {

18             while(low<=high)

19             {

20             int mid=(low+high)>>1;

21             if(A[mid]==target) 

22             {

23                 idx=mid;

24                 return idx;

25             }

26             else if(A[mid]>target)

27             {

28                 high=mid-1;

29             }

30             else low=mid+1;

31             }

32             

33         }

34         else

35         {

36             int mid=(low+high)>>1;

37             if(A[mid]==target)

38             {

39              idx=mid;

40             return idx;

41                 

42             }

43             else 

44             {

45                 idx=bsearch(A,target,low,mid-1);

46                 if(idx==-1)

47                 {

48                     idx=bsearch(A,target,mid+1,high);

49                     

50                 }

51                 

52                 

53                 

54                 

55             }

56             

57             

58             

59             

60             

61             

62         }

63         

64         return idx;

65         

66         

67     }

68     }
View Code

 

 

 

你可能感兴趣的:(LeetCode)