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
2. Solution
classSolution:defsearch(self, nums: List[int], target:int)->int:ifnot nums:return-1deffind_rotate_position(nums, l, r):
mid = r-l+1while l <= r:if nums[l]> nums[r]:
mid =(l+r+1)//2if nums[l]< nums[mid]:
l = mid +1else:
r = mid -1else:return mid
import bisect
rotate_index = find_rotate_position(nums,0,len(nums)-1)if rotate_index !=len(nums)and nums[rotate_index]== target:return rotate_index
else:
i = bisect.bisect_left(nums, target,0, rotate_index)if i !=len(nums)and nums[i]== target:return i
else:if rotate_index <len(nums):
i = bisect.bisect_left(nums, target, rotate_index+1,len(nums))if i !=len(nums)and nums[i]== target:return i
return-1
binary search - leetcode 33. Search in Rotated Sorted Array
1. questionSuppose 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 ret