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.
1 class Solution { 2 public: 3 int search(int A[], int n, int target) { 4 int start = 0, end = n - 1, mid; 5 while (start <= end) { 6 mid = (start + end) / 2; 7 if (A[mid] == target) { 8 return mid; 9 } else if (A[start] <= A[mid]) { 10 if (A[start] <= target && A[mid] > target) { 11 end = mid - 1; 12 } else { 13 start = mid + 1; 14 } 15 } else { 16 if (A[mid] < target && A[end] >= target) { 17 start = mid + 1; 18 } else { 19 end = mid - 1; 20 } 21 } 22 } 23 return -1; 24 } 25 };
通过区间首末元素的大小关系可以确定在该区间内是否有rotate。若进行过翻转则首元素必大于末元素。
复杂在于边界的确定,要注意什么时候需要包括“=”。