leetcode414-- 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.



class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
### method1
#nums = list(set(nums))
#nums.sort()

#try:
#    return nums[len(nums)-3]
#except:
#    return nums[-1]

### method2.

max1, max2, max3 = -float("inf"), -float("inf"), -float("inf")

for x in nums:
if x==max1 or x==max2 or x==max3:
continue

if x>max1:
max1, max2, max3 = x, max1, max2
elif x>max2:
max2, max3 = x, max2
elif x>max3:
max3 = x

if max3 != -float("inf"):
return max3
else:
return max1