O(n) time o(1) space python solution


  • 0
    I
    class Solution(object):
        def thirdMax(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            first_max = float('-inf')
            sec_max = float('-inf')
            third_max = float('-inf')
            
            for num in nums:
                if num > first_max and num != sec_max and num != third_max:
                    third_max = sec_max
                    sec_max = first_max
                    first_max = num
                    
                elif num > sec_max and num != first_max and num != third_max:
                    third_max = sec_max
                    sec_max = num
                    
                elif num > third_max and num != first_max and num != sec_max:
                    third_max = num
                    
            print first_max, sec_max, third_max        
                    
            if third_max == float('-inf'):
                if sec_max != float('-inf'):
                    if first_max != float('-inf'):
                        return first_max
                    return sec_max
                return first_max
    
            return third_max

Log in to reply
 

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