414. Third Maximum Number
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).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
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.
思路:
就是一个排序,用 set 可以直接消除重复的数字,如过长度小于 3 则肯定没有第三个大的值,返回最大值即可,如果长度达大于 3,则返回第三个大的值就行了。
Tips:
之前使用 set() 处理只包含数字的列表,默认是消除重复的元素然后按照数字大小顺序排列,但是当处理的列表中同时存在正数和负数时,set则是正数按大小排在前,负数按大小顺序排在后,第一次提交就卡在了同时正负数的这种情况。
例如:
L=[4,2,3,3,-1,-13,-4]
set(L) = {2, 3, 4, -13, -4, -1}
所以 set(nums) 外要额外加一个 sorted()函数来重新排序。
代码:
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
if len(set(nums))<3:
return nums[-1]
else:
return sorted(set(nums))[-3]