A clear Python solution


  • 0
    M

    Maintaining the top three elements in one scan.

    def thirdMax(self, nums):
        try:
            s = list(set(nums))
            m1, m2, m3 = sorted(s[:3], reverse=True)
            for i in s[3:]:
                if i > m1:
                    m1, m2, m3 = i, m1, m2
                elif m1 > i > m2:
                    m2, m3 = i, m2
                elif m2 > i > m3:
                    m3 = i
            return m3
        except:
            return max(nums)

Log in to reply
 

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