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

leet414. Third Maximum Number

2018-03-24 21:35 169 查看
题目:
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).

分析:
通过集合运算获得所有元素唯一的列表,时间复杂度为O(n)
将新列表长度小于等于3,作为特例处理
采用选择排序算法,由于只获取第三大的值,因此此过程时间复杂度为O(n)

代码:class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret = 0
uniqueNums = list(set(nums))
if len(uniqueNums) < 3:
return max(uniqueNums)
if len(uniqueNums) == 3:
return min(uniqueNums)
for i in range(3):
for j,x in enumerate(uniqueNums[1:]):
if uniqueNums[j] > uniqueNums[j + 1]:
uniqueNums[j],uniqueNums[j + 1] = uniqueNums[j + 1],uniqueNums[j]
ret = uniqueNums.pop()
return ret
思考:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息