33. Search in Rotated Sorted Array
Posted Premiumlab
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了33. Search in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/search-in-rotated-sorted-array/#/description
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.
Sol :
A sorted array is rotated. It must be one of the two conditions.
[6,7,1,2,3,4,5]
Figure 1
[3,4,5,6,7,1,2]
Figure 2
According to two figures above, if A[left] <= A[mid] then [left, mid] must be an ascending array.
We are going to implement it using binary search.
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # binary search first = 0 last = len(nums) - 1 while first <= last: mid = (last+first)/2 if nums[mid] == target: return mid # See figure 2 if nums[first] <= nums[mid]: if nums[first] <= target < nums[mid]: last = mid - 1 else: first = mid + 1 # see figure 1 else: if nums[mid] < target <= nums[last]: first = mid + 1 else: last = mid - 1 return -1
以上是关于33. Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
33. Search in Rotated Sorted Array
33. Search in Rotated Sorted Array *HARD*
33. Search in Rotated Sorted Array
Leetcode[33]-Search in Rotated Sorted Array