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
解题思路:
每次从中间划分后,必然有一个为升序序列,一个为旋转序列,对于升序序列而言,二分法是我们熟悉的,其最小值和最大值也很好判断,因此我们直接判断target是否在升序序列那边,不在的话就在旋转序列。
首先比较mid的值与right的值,由此判断右半部是否为旋转序列:
①若nums[mid] < nums[right],有右部分为升序序列。
对右部分而言,最小值为nums[mid],最大值为nums[right],假设target介于之间,有target在右半部,否则为左半部。
②若nums[mid] >= nums[right],有右部分为旋转序列,那么就对左半部(升序序列)进行分析
对左部分而言,最小值为nums[left],最大值为nums[mid],假设target介于之间,有target在左半部,否则为右半部。
C++
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left <= right){
int mid = left + ((right - left) >> 1);
if(nums[mid] == target)
return mid;
if(nums[mid] < nums[right]){
if(nums[mid] < target && target <= nums[right])
left = mid + 1;
else
right = mid - 1;
}
else{
if(nums[left] <= target && target < nums[mid])
right = mid - 1;
else
left = mid + 1;
}
}
return -1;
}
};
Python
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) >> 1
if nums[mid] == target:
return mid
if nums[mid] < nums[right]:
if nums[mid] < target and target <= nums[right]:
left = mid + 1
else:
right = mid - 1
else:
if nums[left] <= target and target < nums[mid]:
right = mid -1
else:
left = mid + 1
return -1