Clean Python code with O(n)


  • 0
    M
    class Solution(object):
        def findMin(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            
            len_nums = len(nums)
            nums.append(float('inf'))
            
            for i in range(len_nums):
                if nums[i] > nums[i+1]:
                    return nums[i+1]
            
            return nums[0]
    

    For example:

    5 6 7 0 1 2 3 4

    I use a little trick to avoid out of range -> 5 6 7 0 1 2 3 4 inf

    And if nums[i] < nums[i+1] means finding the pivot. So the minimum number should be nums[i+1]

    But if did not find any sequence, it means nums did not rotate.

    Like this: 0 1 2 3 4 5 6 7

    So the minimum number should be the first number in nums.


Log in to reply
 

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