https://leetcode.com/problems/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.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2]
, target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2]
, target = 3
Output: -1
Solution
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.empty())
return -1;
if(nums.size() == 1)
{
if(nums[0] == target)
return 0;
else
return -1;
}
int minIndex = findMinIndex(nums);
if((target >= nums[0]) && (target <= nums[minIndex]))
return binarySearch(nums, 0, minIndex, target);
else if((target >= nums[minIndex + 1]) && (target <= nums[nums.size() - 1]))
return binarySearch(nums, minIndex + 1, nums.size() - 1, target);
else
return -1;
}
private:
int binarySearch(vector<int>& nums, int l, int r, int target)
{
while(l <= r)
{
int mid = (l + r) /2;
if(nums[mid] == target)
return mid;
else if(nums[mid] >= target)
r = mid - 1;
else
l = mid + 1;
}
return -1;
}
int findMinIndex(vector<int>& nums)
{
int l = 0;
int r = nums.size() - 1;
while(l <= r)
{
int mid = (l + r) / 2;
if(mid == nums.size() - 1)
return 0;
else if(nums[mid] > nums[mid + 1])
return mid;
else
{
if(nums[mid] <= nums[nums.size() - 1])
r = mid - 1;
else
l = mid + 1;
}
}
return l;
}
};