LeetCode #414: Third Maximum Number
来源:互联网 发布:三只眼 漫画 知乎 编辑:程序博客网 时间:2024/05/01 14:42
Problem Statement
(Source) 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: 1Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]Output: 1Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.
Solution
Keep three variables to record the biggest three (if exists) numbers. The time complexity is
class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ first, second, third = None, None, None for i in xrange(len(nums)): if first == None: first = nums[i] elif second == None: if nums[i] != first: first, second = sorted([first, nums[i]], reverse=True) elif third == None: if nums[i] not in (first, second): first, second, third = sorted([first, second, nums[i]], reverse=True) else: if nums[i] not in (first, second, third): first, second, third = sorted([first, second, third, nums[i]], reverse=True)[:3] return first if third == None else third
0 0
- LeetCode #414: Third Maximum Number
- Leetcode Third Maximum Number 414
- [LeetCode]414 Third Maximum Number
- LeetCode 414 --- Third Maximum Number
- Leetcode 414:Third Maximum Number
- [LeetCode 414] Third Maximum Number
- Leetcode 414 Third Maximum Number
- LeetCode 414 Third Maximum Number
- LeetCode.414 Third Maximum Number
- LeetCode Third Maximum Number
- LeetCode-Third Maximum Number
- [Leetcode] Third Maximum Number
- LeetCode: Third Maximum Number
- leetcode---Third Maximum Number
- LeetCode : Third Maximum Number
- leetcode[Third Maximum Number]
- LeetCode Third Maximum Number
- leetCode-Third Maximum Number
- C++小例子
- c#学习 1/22 c#语言介绍
- Web分页工具类
- 汉语编程能给我们带来什么?
- 蓝桥杯 算法训练 最大最小公倍数
- LeetCode #414: Third Maximum Number
- window下cmd命令行的使用
- 大数据Spark“蘑菇云”项目实战第63课: 广告点击系统高可用性和性能优化 checkpoint wal driver高可用 并行度配置
- c#学习 2/22 c#基础介绍
- 【Java】三目运算返回值类型测试
- 浅谈 java线程 和 linux进程
- 计算机更新这么快,怎么编程语言还是二十多年前的?
- Xcode错误:Embedded binary's bundle identifier is not prefixed with the parent app's bundle identifier
- 哪些你熟知的重要知识或方法,外人却常常因不了解而陷入困境?