Python solution - time O(n) space O(1)


  • 1
    C
    class Solution(object):
        def thirdMax(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            max_val = [-float("inf") for i in range(3)]
            for i in range(len(nums)):
                if nums[i]>max_val[0]:
                    max_val.insert(0, nums[i])
                    max_val.pop(-1)
                if nums[i]<max_val[0] and nums[i]>max_val[1]:
                    max_val.insert(1, nums[i])
                    max_val.pop(-1)
                if nums[i]<max_val[1] and nums[i]>max_val[-1]:
                    max_val[-1] = nums[i]
            if max_val[-1]!=-float("inf"):
                return max_val[2]
            else:
                return max_val[0]
    

Log in to reply
 

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