Third Maximum Number

Problem Id: 414 Difficulty: Easy


Intuition

Solution


class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        ans = []
        for num in set(nums):
            if len(ans) < 3:
                ans.append(num)
                ans.sort()
            elif num > min(ans):
                ans.append(num)
                ans.sort()
                ans.pop(0)
        return ans[0] if len(ans) == 3 else ans[-1]