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
思考:
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
思考:
相关文章推荐
- Shell 助力开发效率提升
- 十篇笔记走向Python测试开发之路四(字典)
- 十篇python笔记带你走向测试开发之路-第一篇
- mac os 使用pyenv管理python多版本
- Python学习笔记015——序列(字节数组 bytearray)
- 自定义日志
- 日志回滚:python(日志分割)
- python 连接 SAP HANA 数据库
- centos下安装python的过程
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- Python之scrapy实现的爬虫,百度贴吧的自动签到和自动发帖、自动回帖
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- 浅析时钟向量算法