Search in Rotated Sorted Array
Total Accepted: 9935 Total Submissions: 35479Suppose 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 Sorted Array了,认真画了图(左边一个梯形,右边一个三角形(横轴x,纵轴A[x])),然后觉得以我的智商还是乖乖多分几种情况讨论吧。
class Solution {
public:
int search(int A[], int n, int target) {
return bsearch(A, 0, n - 1, target);
}
int bsearch(int A[], int l, int r, int target) {
int mid = (l + r) >> 1;
int tmp = A[mid];
if (l == r && tmp != target)
return -1;
if (tmp == target)
return mid;
else if (tmp >= A[l]) {
if (A[l] <= target && target < tmp)
return bsearch(A, l, mid - 1, target);
else
return bsearch(A, mid + 1, r, target);
}
else {//tmp <= A[r]
if (tmp < target && target <= A[r])
return bsearch(A, mid + 1, r, target);
else
return bsearch(A, l, mid - 1, target);
}
}
};