题目描述
(leetcode题目链接:搜索旋转数组)
整数数组 nums 按升序排列,数组中的值 互不相同 。
在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。
给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 。
举例
示例 1:输入:nums = [4,5,6,7,0,1,2], target = 0 输出:4
示例 2:输入:nums = [4,5,6,7,0,1,2], target = 3 输出:-1
示例 3:输入:nums = [1], target = 0 输出:-1
解题思路: 二分查找。寻找升序的搜索区间,找到target对应的升序搜索空间。
代码
#include <iostream>
#include <vector>
int bin_search(const std::vector<int>& nums, int target) {
int n = nums.size();
if (n <= 0) {
return -1;
}
int left = 0;
int right = n - 1;
while (left <= right) { //搜索区间为[left, right]
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[left] < nums[mid]) { // 前半部分为递增区间
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else { //后半部分为递增区间
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
void print_result(const std::vector<int>&nums, int target, int result) {
// input
std::cout << "========" << std::endl;
std::cout << "input:" << std::endl;
std::cout << "nums: ";
for (auto num : nums) {
std::cout << num << " ";
}
std::cout << ", target: " << target << std::endl;
std::cout << "output:" << std::endl;
std::cout << "result: " << result << std::endl;
}
int main()
{
// case1: nums = [4,5,6,7,0,1,2], target = 0 ==> 4
std::vector<int> nums = {4, 5, 6, 7, 0, 1, 2};
int target = 0;
int result = bin_search(nums, target);
print_result(nums, target, result);
// case2: nums = [4,5,6,7,0,1,2], target = 3 ==> -1
nums = {4, 5, 6, 7, 0, 1, 2};
target = 3;
result = bin_search(nums, target);
print_result(nums, target, result);
// case1: nums = [4,5,6,7,0,1,2], target = 4 ==> 0
nums = {4, 5, 6, 7, 0, 1, 2};
target = 4;
result = bin_search(nums, target);
print_result(nums, target, result);
return 0;
}
代码运行结果如下:
========
input:
nums: 4 5 6 7 0 1 2 , target: 0
output:
result: 4
========
input:
nums: 4 5 6 7 0 1 2 , target: 3
output:
result: -1
========
input:
nums: 4 5 6 7 0 1 2 , target: 4
output:
result: 0