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.
ps:这题和剑指offter的题目类似。一次AC
思路,由于没有重复数字,
1.我们先找出最大值在哪个位置。
2.然后拿target和A[0]做比较,若target>A[0],则在0~max_loc之间来二分查找数组;若target<A[0],则在max_loc+1~n-1来查找数组。
代码:
class Solution { public: int binarySearch(int start,int end,int A[],int target){ int l=start;int r=end;int mid=0; while(l<=r){ mid=(l+r)/2; if(A[mid]>target) r=mid-1; else if(A[mid]<target) l=mid+1; else return mid; } return -1; } int findMaxValueLoction(int A[],int n){ if(A[n-1]>A[0]) return n-1; int l=0;int r=n-1;int mid=0; while(l<=r){ mid=(l+r)/2; if(mid==0) return mid; else if(mid!=0&&A[mid]>A[0]&&A[mid]>A[mid-1]&&A[mid]<A[mid+1]){ l=mid+1; } else if(mid!=0&&A[mid]<A[0]&&A[mid]>A[mid-1]&&A[mid]<A[mid+1]){ r=mid-1; } else if(mid!=0&&A[mid]>A[mid-1]&&A[mid]>A[mid+1]){ return mid; }else{ return mid-1; } } return -1; } int search(int A[], int n, int target) { if(A==NULL||n==0) return -1; int max_loc=findMaxValueLoction(A,n); if(target>A[0]) return binarySearch(0,max_loc,A,target); else if(target<A[0]) return binarySearch(max_loc+1,n-1,A,target); else return 0; } };