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.
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
Solution
思路:
- 因为时间复杂度要求
O(log n)
,因此只能考虑Binary Search,二分搜索 - 第一步,先找到pivot的位置,也就数组中最小元素的位置
if a[mid] > a[hi]
,最小元素在mid
的右侧,lo = mid + 1
.if a[mid] <= a[hi]
,最小元素在mid
的左侧,hi = mid
.
- 根据找到的pivot的位置,进行正常的二分搜索
real_mid = (mid + pivot) % lens
相当于把原数组一一映射成为已经排好序的数组.
class Solution:
def search(self, nums, target):
lens = len(nums)
lo, hi = 0, lens-1
# find pivot
while lo < hi:
mid = int((lo + hi) / 2)
if nums[mid] > nums[hi]:
lo = mid + 1
else:
hi = mid
pivot = lo
# normal binary search
lo, hi = 0, lens-1
while lo <= hi:
mid = (lo + hi) >> 1
real_mid = (mid + pivot) % lens
if nums[real_mid] == target:
return real_mid
if nums[real_mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
s = Solution()
result = s.search([4, 5, 6, 7, 0, 1, 2], 0)
print(result)