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.
题意:一个已经排序好的数组,被按某个位置旋转了一次,给定一个值target,在该旋转后的数组里查找该值。
思路:二分查找
int search(int A[], int n, int target){ int start = 0, end = n, middle ; while(start < end){ middle = (start + end) / 2; if(A[middle] == target) return middle; if(A[middle] >= A[start]){ if(target >= A[start] && target < A[middle]){ end = middle; }else{ start = middle + 1; } }else{ if(target > A[middle] && target <= A[end - 1]){ start = middle + 1; }else{ end = middle; } } } return -1; }