Leetcode 33. Search in Rotated Sorted Array

https://leetcode.com/problems/search-in-rotated-sorted-array/css

Medium

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]

  • 二分查找。理解二分查找的原理,若在單調區間內,則正常二分縮小範圍,不然針對邊界進行變種的修改。經過座標圖能更容易理解算法。
  • 須要注意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
 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
View Python Code
相關文章
相關標籤/搜索