Leetcode "Find Minimum in rotated Sorted Array" Python implementation

Source: Internet
Author: User

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 ).

Find the minimum element.

Assume no duplicate exists in the array.

code : OJ Test via runtime:52 ms

1 classSolution:2     #@param num, a list of integers3     #@return An integer4     deffindmin (self, num):5         #None case6         ifNum isNone:7             returnNone8         #Short Lenght case9         ifLen (num) ==1 :Ten             returnNum[0] One         #binary Search AStart =0 -end = Len (num)-1 -          whilestart<=End: the             ifstart==End: -                 returnNum[start] -             ifstart+1==End: -                 returnmin (num[start],num[end]) +Mid = (start+end)/2 -             ifNum[mid]>Num[start]: +                 ifNum[mid]>Num[end]: AStart =Mid at                 Else: -                     returnNum[start] -             Else: -                 ifNum[mid]>Num[end]: -                     returnNum[end] -                 Else: inEnd = Mid

Ideas :

The basic idea is binary search.

Note the condition when you modify start or end: Because mid can also be the smallest value, so Start=mid End=mid, which differs from the traditional binary search start=mid+1 and end=mid-1.

To understand these, code once AC.

Leetcode "Find Minimum in rotated Sorted Array" Python implementation

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.