Leetcode: 33. Search in Rotated Sorted Array
Description
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.
思路
- 二分查找
- 有两个关键,由于数组经过旋转过,所以应该先判断mid落在前半段还是后半段
- 然后再根据target的大小判断怎么缩小范围
代码
class Solution {
public:
int search(vector<int>& nums, int target) {
int len = nums.size();
if (len == 0) return -1;
int low = 0, high = len - 1, mid = 0;
while (low <= high){
mid = low + (high - low) / 2;
if (nums[mid] == target) return mid;
//落在前半段
if (nums[mid] >= nums[low]){
//落在前半段的前半段
if (nums[low] <= target && target < nums[mid])
high = mid - 1;
else low = mid + 1;
}
else{
//落在后半段的后半段
if (nums[mid] < target && target <= nums[high])
low = mid + 1;
else high = mid - 1;
}
}
return -1;
}
};