Python Solution in One Pass


  • 0
    S
    class Solution(object):
        def thirdMax(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            nums = list(set(nums))
    
            if len(nums) < 3:
                if len(nums) == 1:
                    return nums[0]
                else:
                    return max(nums[0], nums[1])
            
            maxi = float("-inf")
            secondmaxi = float("-inf")
            thirdmaxi = float("-inf")
            
            for i in xrange(0, len(nums)):
                if nums[i] > maxi:
                    thirdmaxi = secondmaxi
                    secondmaxi = maxi
                    maxi = nums[i]
                elif nums[i] > secondmaxi:
                    thirdmaxi = secondmaxi
                    secondmaxi = nums[i]
                elif nums[i] > thirdmaxi:
                    thirdmaxi = nums[i]
            return thirdmaxi

Log in to reply
 

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