您的位置:首页 > 编程语言 > Python开发

[leetcode: Python]414. Third Maximum Number

2017-05-16 17:34 239 查看
Title:

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.


方法一:56ms

class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

n1 = set(nums)
s1 = []
for i in n1:
s1.append(i)
s1.sort()
s = s1[::-1]
if len(s) < 3:
return s[0]

return s[2]


方法二:39ms

class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a=set(nums)
if len(a)<3: return max(a)
else:
a.remove(max(a))
a.remove(max(a))
return max(a)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: