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.
题意:在一个已经排好序,但是中间翻转过得数组中找目标思路:首先对于left和right看看,A[left] <= A[right]的话那么证明这段数组是有序的,否则的话,就是一个有折点的数组,再在左右两段中继续二分
class Solution { public: int search(int A[], int n, int target) { return find(A, 0, n-1, target); } int find(int A[], int l, int r, int target) { if (l > r) return -1; int ans = -1; if (A[l] <= A[r]) { int left = l, right = r; while (left <= right) { int mid = left + right >> 1; if (A[mid] == target) { ans = mid; break; } if (A[mid] > target) right = mid - 1; else left = mid + 1; } } else { int mid = l + r >> 1; if (A[mid] == target) ans = mid; else { ans = find(A, l, mid - 1, target); ans = ans == -1 ? find(A, mid + 1, r, target) : ans; } } return ans; } };
LeetCode Search in Rotated Sorted Array
原文:http://blog.csdn.net/u011345136/article/details/43991047