Who has a better Python solution?


  • 0
    P

    Here is mine log(n) solution:

    class Solution:
        # @param num, a list of integer
        # @return an integer
        def findMin(self, num):
            n=len(num)
            strt=0
            nd=n-1
            while num[strt]>num[nd]:
                mid=(strt+nd)//2
                if num[strt]>num[mid]:
                    nd=mid
                elif num[strt]<num[mid]:
                    strt=mid
                else:
                    return num[nd]
            return num[strt]

  • 0
    R

    Not saying mine is better, however here it comes using recursion:

    class Solution:
        # @param num, a list of integer
        # @return an integer
        def findMin(self, num):
            if len(num) == 1 or num[0] < num[-1]:
                return num[0]
            return self.min(num, 0, len(num)-1)
            
        def min(self, num, a, b):
            if a+1 == b: return min(num[a], num[b])
            if num[a] > num[(a+b)/2]:
                return self.min(num, a, (a+b)/2)
            else:
                return self.min(num, (a+b)/2, b)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.