Python O(n) time, O(1) space.

  • 9
    import sys
    class Solution(object):
        def thirdMax(self, nums):
            :type nums: List[int]
            :rtype: int
            one = two = three = -sys.maxint
            for i in nums:
                if i > one:
                    one, two, three = i, one, two
                elif i > two and i < one:
                    two, three = i, two
                elif i > three and i < two:
                    three = i
            return three if three != -sys.maxint else one

Log in to reply

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