题目:
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.
class Solution {
public:
int search(int A[], int n, int target) {
int ans = searchHelper(A, 0, n - 1, target);
return ans;
}
private:
int searchHelper(int A[], int low, int high, int target) {
int idx = -1;
if(low > high)
return -1;
if (A[low] <= A[high]) {
while (low <= high) {
int mid = (low + high) / 2;
if (A[mid] == target) {
idx = mid;
break;
}
else if (A[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
}
else {
int mid = (low + high) / 2;
if (A[mid] == target)
idx = mid;
else {
idx = searchHelper(A, low, mid - 1, target);
idx = idx == -1 ? searchHelper(A, mid + 1, high, target) : idx;
}
}
return idx;
}
};
本文介绍了一种在旋转排序数组中查找目标值的算法实现。该算法通过递归辅助函数进行二分查找,并处理了数组旋转带来的复杂性。文章提供了一个C++类实现,包括主要搜索函数及其辅助函数。
439

被折叠的 条评论
为什么被折叠?



