题解 | #在旋转过的有序数组中寻找目标值#
在旋转过的有序数组中寻找目标值
https://www.nowcoder.com/practice/87c0e7abcbda41e7963660fa7d020995
符合题目时间复杂度要求的二分法求解。
#include<algorithm>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @param target int整型
* @return int整型
*/
int search_fold(vector<int> nums, int left, int right, int target) {
if (right == left) {
if (nums[right] == target) {
return right;
} else {
return -1;
}
}
// bipartition the input range, find the ordered range
int mid = (left + right) / 2;
int fold_left, fold_right;
int order_left, order_right;
if (nums[mid] < nums[left]) {
fold_left = left;
fold_right = mid - 1;
order_left = mid;
order_right = right;
} else {
fold_left = mid + 1;
fold_right = right;
order_left = left;
order_right = mid;
}
// firstly search in the ordered range, then search in the folded range
auto bs_it = lower_bound(nums.begin() + order_left, nums.begin() + order_right,
target);
if (*bs_it == target) {
return bs_it - nums.begin();
} else {
return search_fold(nums, fold_left, fold_right, target);
}
};
int search(vector<int>& nums, int target) {
// write code here
int left(0), right(int(-1) + nums.size());
return search_fold(nums, left, right, target);
}
};


基恩士成长空间 446人发布