414 third maximum number
414. Third Maximum Number
题目: https://leetcode.com/problems/third-maximum-number/
难度:
Easy
思路:
用三个变量来记录,max, secondmax, thirdmax,
- 遇到比max还大的就更新,当前max降级为secondmax,当前secondmax降级为thirdmax
- 遇到比max小但是比secondmax大的也这样做降级处理
- 更thirdmax
AC代码
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m, sm, tm = float('-inf'), float('-inf'), float('-inf')
for num in nums:
if num > m:
tm = sm
sm = m
m = num
elif num < m and num > sm:
tm = sm
sm = num
elif num < m and num < sm and num > tm:
tm = num
return tm if tm != float('-inf') else m