33. Search in Rotated Sorted Array
题目描述:
Suppose an array sorted in ascending order 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.
题解:
二分查找
已排序的数组以某一点为转轴旋转,转轴未知,找到target在数组中的位置。
每次分两种情况,即分界点在中线左边还是右边,并对这两种情况再具体处理。
用first和last来不断缩小查找范围,最后逼近实际位置。
考虑数值范围明显可知的区间,即确定哪部分递增
如果前/后半部分递增,情况有两种:
1. target在递增区间
2. target不在此递增区间
由此可确定target具体范围
solution1:
class Solution {
public:
int search(const vector<int>& nums, int target) {
int first = 0;
int last = nums.size();
while (first != last) {
int mid = (first + last) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[first] <= nums[mid]) { // 前半部分递增
if (nums[first] <= target && target < nums[mid]) { // target在递增部分(可直接确定范围)
last = mid;
} else {
first = mid + 1;
}
} else { // 后半部分递增
if (nums[mid] < target && target <= nums[last-1]) {
first = mid + 1;
} else {
last = mid;
}
}
}
return -1;
}
};