# Intuitive and Short Python solution

• ``````class Solution(object):
def thirdMax(self, nums):
v = [float('-inf'), float('-inf'), float('-inf')]
for num in nums:
if num not in v:
if num > v[0]:   v = [num, v[0], v[1]]
elif num > v[1]: v = [v[0], num, v[1]]
elif num > v[2]: v = [v[0], v[1], num]
return max(nums) if float('-inf') in v else v[2]
``````

Time complexity is O(n), space complexity is O(1).

• I like this solution. Very clean and easy to read. Better than the set solution imo.

• elif num > v[1]: v = [v[0], num, v[1]]

is it elif num > v[1]: v = [v[0], num, v[2]]?

• So easy to understand, great job.

• Nice solution! It is smart to put the first 3 largest numbers in a list.Here is my another solution using sort.

`````` if len(set(nums))<3: return max(nums)
nums.sort(reverse=True)
count=1
for i in range(len(nums)):
if nums[i+1]!=nums[i]:
count+=1
if count==3:
return nums[i+1]
``````

• class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(set(nums))<3:
return max(nums)
return heapq.nlargest(3,list(set(nums)))[2]

• I wrote similar code:

``````    def thirdMax(self, nums):
a = b = c = -float("inf")
for n in nums:
if n in (a, b, c): continue
if n > a: n, a = a, n
if n > b: n, b = b, n
if n > c: n, c = c, n
return a if c == -float("inf") else c
``````

• @werwolfxst once you use sort, it's not O(n) anymore right?

• @agave wow my solution looks like crap compare to this. Good one

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