[Leetcode] 414. Third Maximum Number 解题报告
来源:互联网 发布:vs2017 java 编辑:程序博客网 时间:2024/06/10 08:37
题目:
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.
思路:
可以用自动排序以及去重的set来实现:遍历数组的每个元素,并且将其加入set中,一旦发现set的个数超过3个,则移除掉最小的一个。由于我们保证了set的规模不超过4,所以整个算法的时间复杂度是O(n),空间复杂度是O(1)。
代码:
class Solution {public: int thirdMax(vector<int>& nums) { set<int> top_3; for (auto num : nums) { top_3.insert(num); if (top_3.size() > 3) { top_3.erase(top_3.begin()); } } return top_3.size() == 3 ? *top_3.begin() : *top_3.rbegin(); }};
阅读全文
0 0
- [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 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-414. Third Maximum Number
- [leetcode]414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- [LeetCode]414. Third Maximum Number
- 基于python的spark mongodb
- LeetCode | 83. Remove Duplicates from Sorted List
- mysql 查询出多级父级内容和多级子级内容
- 『 Spark 』1. spark 简介
- android 7.0适配
- [Leetcode] 414. Third Maximum Number 解题报告
- linux logrotate 日志切割管理
- kaggle+mnist手写字体识别
- Paint Canvas 类属性方法学习笔记
- 分布式之消息队列
- JDK源码中的help GC 与 JVM的可达性算法分析
- JS数组去重的几种方法
- MySQL之选择字段数据类型
- uploadify_V2.1.0上传文件并携带参数