Leetcode 33. Search in Rotated Sorted Array
https://leetcode.com/problems/search-in-rotated-sorted-array/
Medium
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
- 二分查找。理解二分查找的原理,若在单调区间内,则正常二分缩小范围,否则针对边界进行变种的修改。通过坐标图能更容易理解算法。
- 需要注意code里两次用到<=的地方
- while left <= right,保证了如果循环结束,结果必然是left > right,i.e. 没有找到target。
- if nums[left] <= nums[middle]:,因为middle = (left + right) // 2是向下取整,所以需要用<=,e.g. [2, 0], 0
- https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14436/Revised-Binary-Search
- 6. Expressions — Python 3.7.4 documentation
- https://docs.python.org/3/reference/expressions.html#comparisons
- Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < 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