/*
33. Search in Rotated Sorted Array My Submissions QuestionEditorial Solution
Total Accepted: 98590 Total Submissions: 326117 Difficulty: Hard
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.
Subscribe to see which companies asked this question
*/
/*
解题思路:
旋转数组的元素查找,依然采用折半查找
比非旋转数组多了一层判断
if(右半边有序){
if(target在右半边){
left=mid+1;
}
else{
right=mid-1;
}
//左半边有序
}else{
if(target在左半边){
right=mid-1;
}
else{
left=mid+1;
}
}
*/
class Solution {
public:
int search(vector<int>& nums, int target) {
//旋转数组中查找数字,使用折半查找法
if(nums.empty())return -1;
int left=0,right=nums.size()-1;
int mid;
while(left<=right){
mid=left+(right-left)/2;
if(nums[mid]==target)return mid;
//右半边有序
else if(nums[mid]<nums[right]){
if(nums[mid]<target&&nums[right]>=target)left=mid+1;
else right=mid-1;
//左半边有序
}else{
if(nums[mid]>target&& nums[left]<=target)right=mid-1;
else left=mid+1;
}
}
return -1;
}
};