Search in Rotated Sorted Array
题目:
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.
题意:
给定一个排序的数组,比如0,1,2,4,5,6,7,现在以中间的某个点旋转,结果为4,5,6,7,0,1,2,在旋转后的数组中找给定的target数值的下标index,如果不存在则返回-1。
思路:
原本数组是左图,现数组是右图,我们还是用二分查找来解决,不过需要注意转折点,在每次二分的时候都需要判断是否包含转折点(右图虚线),如果不包含,说明我们在右图虚线的左边或右边,可以用正常二分,如果包含,那么不断缩小范围直到不包含转折点为止。题目关键就是需要判断转折点。
代码:
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.size() == 0){
return -1;
}
int left = 0;
int right = nums.size()-1;
int mid = 0;
while(left <= right){
//可避免越界
mid = left + (right-left)/2;
if(nums[mid] == target){
return mid;
}else if(nums[right] < nums[mid]){
//说明转折点在右边
if(target >= nums[left] && target < nums[mid]){
//二分
right = mid-1;
}else{
left = mid+1;
}
}else{
//说明转折点在左边
if(target > nums[mid] && target <= nums[right]){
left = mid+1;
}else{
right = mid-1;
}
}
}
return -1;
}
};