Third Maximum Number
Input:
[3, 2, 1]
Output:
1
Explanation:
The third maximum is 1.Input:
[1, 2]
Output:
2
Explanation:
The third maximum does not exist, so the maximum (2) is returned instead.题目大意:
解题思路:
Last updated
Input:
[3, 2, 1]
Output:
1
Explanation:
The third maximum is 1.Input:
[1, 2]
Output:
2
Explanation:
The third maximum does not exist, so the maximum (2) is returned instead.Last updated
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
"""
p1 = p2 = p3 = None
for num in nums:
if num > p1:
p1,p2,p3=num,p1,p2
elif p1 > num > p2:
p2,p3 = num,p2
elif p2>num>p3:
p3 = num
return p3 if p3 != None else p1def thirdMax(self, nums):
nums = set(nums)
if len(nums) < 3:
return max(nums)
nums.remove(max(nums))
nums.remove(max(nums))
return max(nums)