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).
给一个数组,找到第三大的值,如果没有就返回最大值。这里的值是有并列的,
[2, 2, 3, 1]->1而不是2
class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ d = {} for value in nums: d[value] = 1 first_max = float('-inf') second_max = float('-inf') third_max = float('-inf') for key,value in d.items(): if key > first_max: third_max = second_max second_max = first_max first_max = key elif key > second_max: third_max = second_max second_max = key elif key > third_max: third_max = key return third_max if third_max != float('-inf') else first_max