414. Third Maximum Number
时间:2020-07-15 01:19:01
收藏:0
阅读:57
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
原文:https://www.cnblogs.com/whatyouthink/p/13302987.html
评论(0)