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.
There solutions:
Solution 1:how to hand the specific case involved point A, B and C?
Solution 2:how to hand the specific case involved point A, ND d?
Solution 1:
classSolution:#@param A, a list of integers #@param target, an integer to be searched #@return An integer defSearch (self, A, target):returnSelf.helper (A, target, 0, Len (a)-1) defHelper (self, A, target, Low, high):ifLow > High:return-1Mid= (low + high)/2iftarget = = A[mid]:returnMidelifA[low] <= Target < A[mid]or(A[mid] <= A[high] and(Target < A[mid]orTarget >A[high]):returnSelf.helper (A, Target,low, mid-1) Else: returnSelf.helper (A, target,mid+1, High)
Solution 2:
classSolution:#@param A, a list of integers #@param target, an integer to be searched #@return An integer defSearch (self, A, target): Low,high= 0,len (A)-1 whileLow <=High:mid= (low+high+1)/2ifA[mid]==target:returnMidifA[low] <=A[mid]:ifA[low] <= Target < A[mid]: high=mid-1Else: low=mid+1Else: ifA[mid] < target <= A[high]: low=mid+1Else: high=mid-1return-1
[Leetcode] Search in rotated Sorted Array @ Python [figure][with illustration description]