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.
Subscribe to see which companies asked this question
分析如下
- 注意上图中的“实际又递归了函数”的意思是递归了“查找旋转数组”
- 另外两种情况,“查找顺序数组”
Python
# 非递归版 情况较多,不好理解
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
#print(mid, nums[mid])
if nums[mid] == target:
return mid
#这里需要判断mid在左半段还是右半段
#而不是判断target的大小关系
elif nums[mid] < nums[right]: #nums[mid:right] sorted
if nums[mid] <= target <= nums[right]:
left = mid + 1
else:
right = mid - 1
else:
if nums[left] <= target <= nums[mid]:
right = mid - 1
else:
left = mid + 1
return -1
# 递归版
import sys
sys.setrecursionlimit(1500)
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return self.searchFunc(nums, 0, len(nums)-1, target)
def searchFunc(self, nums, left, right, target):
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < nums[right]:
if nums[mid] <= target <= nums[right]:
self.searchFunc(nums, mid+1, right, target)
else:
self.searchFunc(nums, left, mid-1, target)
else:
if nums[left] <= target <= nums[mid]:
self.searchFunc(nums, left, mid-1, target)
else:
self.searchFunc(nums, mid+1, right, target)
return -1
if __name__ == '__main__':
a = [3, 4, 5, 6, 7, 0, 1, 2]
b = [6, 7, 8, 1, 2, 3, 4, 5]
t = 22
p = Solution()
print(p.search(a, t))