Intuitive and Short Python solution

  • 30
    class Solution(object):
        def thirdMax(self, nums):
            v = [float('-inf'), float('-inf'), float('-inf')]
            for num in nums:
                if num not in v:
                    if num > v[0]:   v = [num, v[0], v[1]]
                    elif num > v[1]: v = [v[0], num, v[1]]
                    elif num > v[2]: v = [v[0], v[1], num]
            return max(nums) if float('-inf') in v else v[2]

    Time complexity is O(n), space complexity is O(1).

  • 0

    I like this solution. Very clean and easy to read. Better than the set solution imo.

  • -1

    @agave said in Intuitive and Short Python solution:

    elif num > v[1]: v = [v[0], num, v[1]]

    is it elif num > v[1]: v = [v[0], num, v[2]]?

  • 0

    So easy to understand, great job.

  • 0

    Nice solution! It is smart to put the first 3 largest numbers in a list.Here is my another solution using sort.

     if len(set(nums))<3: return max(nums)
     for i in range(len(nums)):
         if nums[i+1]!=nums[i]:
             if count==3:
                 return nums[i+1]

  • -1

    class Solution(object):
    def thirdMax(self, nums):
    :type nums: List[int]
    :rtype: int
    if len(set(nums))<3:
    return max(nums)
    return heapq.nlargest(3,list(set(nums)))[2]

  • 0

    I wrote similar code:

        def thirdMax(self, nums):
            a = b = c = -float("inf")
            for n in nums:
                if n in (a, b, c): continue
                if n > a: n, a = a, n
                if n > b: n, b = b, n
                if n > c: n, c = c, n
            return a if c == -float("inf") else c

Log in to reply

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