forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththird-maximum-number.py
More file actions
30 lines (26 loc) · 838 Bytes
/
third-maximum-number.py
File metadata and controls
30 lines (26 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Time: O(n)
# Space: O(1)
# Given an array of integers, return the 3rd Maximum Number in this array,
# if it doesn't exist, return the Maximum Number.
# The time complexity must be O(n) or less.
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
top = [float("-inf")] * 3
for num in nums:
if num > top[0]:
top[0], top[1], top[2] = num, top[0], top[1]
count += 1
elif num != top[0] and num > top[1]:
top[1], top[2] = num, top[1]
count += 1
elif num != top[0] and num != top[1] and num >= top[2]:
top[2] = num
count += 1
if count < 3:
return top[0]
return top[2]