title :
Suppose a sorted array is rotated on 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 is given a target value to search. If found in the array is return its index, otherwise return-1.
Assume no duplicate exists in the array
code : OJ Test via runtime:53 ms
1 classSolution:2 #@param A, a list of integers3 #@param target, an integer to be searched4 #@return An integer5 defSearch (self, A, target):6 #None Case & Zero case7 ifA isNoneorLen (A) = =0:8 return-19 #binary SearchTenStart =0 Oneend = Len (A)-1 A whilestart<=End: - #One element left case - ifStart = =End: the ifa[start]==Target: - returnStart - Else: - return-1 + #Elements left case - ifStart+1 = =End: + ifa[start]==Target: A returnStart at elifa[end]==Target: - returnEnd - Else: - return-1 - #equal or more than three elements case -Mid = (start+end)/2 in ifa[mid]==Target: - returnMid to elifA[mid]>Target: + ifA[start]>a[mid] anda[end]<A[mid]: -Start = Mid+1 the elifA[start]<a[mid] anda[end]<A[mid]: * ifa[end]>=Target: $Start = Mid+1Panax Notoginseng Else: -End = Mid-1 the elifA[start]>a[mid] andA[end]>A[mid]: +End = Mid-1 A Else: theEnd = Mid-1 + Else: - ifA[start]>a[mid] anda[end]<A[mid]: $End = Mid-1 $ elifA[start]<a[mid] anda[end]<A[mid]: -Start = Mid+1 - elifA[start]>a[mid] andA[end]>A[mid]: the ifa[end]>=Target: -Start = Mid+1Wuyi Else: theEnd = Mid-1 - Else: WuStart = Mid+1 - return-1
Ideas :
This is the idea of binary search.
The individual did not think out what a good way to bite the bullet hard to write a violent solution.
The traditional binary search only needs to judge A[mid] and target size is OK, but this problem is rotated array, light judgment A[mid] is not enough.
It is also necessary to determine the size of A[start] a[end] and A[mid] in order to determine whether the target may fall within the [Start,mid] or [mid,end] interval.
Your code is a little cumbersome and ugly, and it is estimated that some if else conditions can be merged and subsequently improved.
Leetcode "Search in rotated Sorted Array" Python implementation