https://leetcode.com/problems/search-in-rotated-sorted-array/css
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.html
(i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
).python
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.express
Your algorithm's runtime complexity must be in the order of O(log n).ide
Example 1:ui
Input: nums = [, target = 0 Output: 4 4,5,6,7,0,1,2]
Example 2:lua
Input: nums = [, target = 3 Output: -14,5,6,7,0,1,2]
x < y <= z
is equivalent to x < y and y <= z
, except that y
is evaluated only once (but in both cases z
is not evaluated at all when x < y
is found to be false).1 class Solution: 2 def search(self, nums: List[int], target: int) -> int: 3 if not nums: 4 return -1 5 6 left, right = 0, len(nums) - 1 7 8 # pay attention to <= 9 while left <= right: 10 middle = (left + right) // 2 11 12 if nums[middle] == target: 13 return middle 14 15 # pay attention to <= 16 if nums[left] <= nums[middle]: 17 if nums[left] <= target < nums[middle]: 18 right = middle - 1 19 else: 20 left = middle + 1 21 else: 22 if nums[middle] < target <= nums[right]: 23 left = middle + 1 24 else: 25 right = middle - 1 26 27 return -1