题目
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: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
翻译
给定一个数组,返回数组中的第三大数。如果不存在,则返回最大的数。时间复杂度为O(n)
思路
保持一个大小为3的集合。
遍历数组,然后将元素插入,如果集合大小小于等于3,则继续,如果大于3,则取消set中第一个元素。接着遍历。
分析:
给一个最大为3的插入,删除一个元素的时间复杂度为O(nlogn),在这里即为O(3)。所以时间负责度为O(n)
代码
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();
}
};