human
I found an interesting problem on https://leetcode.com/problems/third-maximum-number/:
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.


Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.


Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

I tried it in Python, but could not do it. Can you solve it?

 ... What is a the Python program you requested?
assistant
#Here is the Python program you requested.

class Solution:
     def thirdMax(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         
         """
         if len(nums) == 2 or len(nums) == 1:
             return max(nums)
         
         maxes = [nums[0], nums[1], nums[2]]
         maxes.sort() # ascending
         
         for i in range(3, len(nums)):
             pos = self.findPos(nums[i], maxes)
             if pos != None:
                 maxes[pos] = nums[i]
                 
         if maxes[0] == maxes[1] or maxes[1] == maxes[2]:
             return maxes[2]
         else:
             return maxes[0]
                 
     
     def findPos(self, val, maxes):
         maxPos = None
         for ind, aMax in enumerate(maxes):
             if val > aMax:
                 maxPos = ind
             
         return maxPos
         """
         
         maxes = []
         
         for i in nums:
             if self.isNew(i, maxes):
                 if len(maxes) < 3:
                     maxes.append(i)
                     maxes.sort() # ascending
                 else:
                     pos = self.findPos(i, maxes)
                     if pos != None:
                         maxes[pos] = i
                         maxes.sort()
         
         if len(maxes) == 3:
             return maxes[0]
         else:
             return maxes[-1]
                 
     
     def isNew(self, val, maxes):
         isNew = True
         for i in maxes:
             if val == i:
                 isNew = False
         return isNew
     
     def findPos(self, val, maxes):
         for ind, aMax in enumerate(maxes):
             if val > aMax:
                 return ind
             
         return None