[Leetcode] Search in rotated Sorted Array @ Python [figure][with illustration description]

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.