LeetCode 414. Third Maximum Number
来源:互联网 发布:淘宝店铺推广平台 编辑:程序博客网 时间:2024/05/22 05:24
Third Maximum Number
题目描述:
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.
题目大意:
给定一个数组,求出数组中第三大的元素。
1:全部放到set中,直接返回倒数第三个数字即可。
2:把元素一个一个往set中插入,直到所有元素插入完成,如果插入元素后长度超过3,那么“擦除”set中第一个元素,这样可以使中保持set中有三个元素。最后输出set中第一个元素也就是“第三大”元素。
需要注意的是,如果set中元素小于3,那么要输出最大的元素。
题目代码:
class Solution {public: int thirdMax(vector<int>& nums) { set<int>s(nums.begin(), nums.end()); set<int>::iterator iter; iter = s.end(); iter--; iter--; iter--; if(s.size() >= 3) return *iter; else return *s.rbegin(); }};
class Solution {public: int thirdMax(vector<int>& nums) { set<int> s; for(int num : nums){ s.insert(num); if(s.size() > 3){ s.erase(s.begin()); } } return s.size() == 3 ? *s.begin() : *s.rbegin(); }};
阅读全文
1 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
- Scene---场景的异步加载
- SmoothDamp与Lerp函数使用问题误区浅析
- linux ps命令
- (CodeForces
- 26. Remove Duplicates from Sorted Array
- LeetCode 414. Third Maximum Number
- 数组Array和操作集合Collections的静态方法;
- 夯实基础
- 环境搭建ssh-maven
- 素数环uva524
- animation动画
- UML
- 连接mysql服务器出现 10038
- 牛客网 求一个整数可以由多少素数对组成