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.
解题思路:这题旋转排序数组,查找目标值并返回其位置。Rotated:A[i] < A[i + 1] < ... < A[N - 1] > A[0] < A[1] < ... < A[i - 1]。方法采用二分查找法,但是必须注意一些情况。循环遍历,若遇到以下情况(1)当A[middle]>=A[index1]时,判断目标值target是否大于等于A[index1]且小于等于A[middle],如此index2=middle;否则index1=middle+1(2)A[middle]<A[index1]时,判断target是否小于A[index2]且target是否大于等于middle,则index1=middle;否则index2=middle-1;最后还有一种情况循环结束后,判断A[index2]是否等于target,如此便可以返回目标值的位置。
class Solution { public: int search(int A[], int n, int target) { if(A==NULL || n==0) return -1; int index1=0; int index2=n-1; int middle; while(index1<index2) { middle=(index1+index2)/2; if(A[middle]>=A[index1]) { if(target>=A[index1]&&target<=A[middle]) index2=middle; else index1=middle+1; } else { if(target<=A[index2]&&target>=A[middle]) index1=middle; else index2=middle-1; } } if(index2>=0 && index2<n && target==A[index2]) return index2; else return -1; } };