题目描述
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
解题思路
看到 O(log n) 的时间复杂度,第一时间想到二分查找。但是给出的列表是局部有序的,我们就需要改变传统的二分的思路。
直接看代码。
代码 (Python 3)
class Solution:
def search(self, nums, target: int) -> int:
if target not in nums:
return -1
left = 0
right = len(nums) - 1
while left <= right: # 开始二分查找
mid = (left + right) // 2
if nums[mid] == target: # 找到即退出
return mid
elif nums[mid] >= nums[left]: # 关键!若此条件满足,则在 [left, mid] 区间为单调
if nums[left] <= target <= nums[mid]:
right = mid
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1