题目描述:
python实现 Search in Rotated Sorted Array 搜索旋转排序数组
中文:假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
英文: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).
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
start = 0
end = len(nums)-1
while start<=end:
mid = (start + end)/2 #对于整数会自动省去小数部分
if nums[mid] == target:
return mid
if nums[mid]>=nums[start]:
if target >= nums[start] and target<=nums[mid]:
end = mid-1
else:
start = mid + 1 if nums[mid]<nums[end]:
if target > nums[mid] and target<=nums[end]:
start = mid+1 else:
end = mid -1
return -1
题目来源:力扣题库