Subject description:
python achieve Search in Rotated Sorted Array sort rotating array of search
Chinese: Suppose ascending order according to the array was rotated in a previously unknown point.
(E.g., array [0,1,2,4,5,6,7] may become [4,5,6,7,0,1,2]).
Searching for a given target value, if the existence of the target array, its index returns, otherwise it returns -1.
You can assume that the array element does not exist in duplicate.
Your time complexity of the algorithm must be O (log n) level.
英文: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).
1 class Solution(object): 2 def search(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: int 7 """ 8 start = 0 9 end = len(nums)-1 10 while start<=end: 11 mid = (start + end)/2 #对于整数会自动省去小数部分 12 if nums[mid] == target: 13 return mid 14 if nums[mid]>=nums[start]: 15 if target >= nums[start] and target<=nums[mid]: 16 end = mid-1 17 else: 18 start = mid + 1 19 20 if nums[mid]<nums[end]: 21 if target > nums[mid] and target<=nums[end]: 22 start = mid+1 23 24 else: 25 end = mid -1 26 return -1
Topic Source: stay button Exam