题目
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.
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.
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.
思路
1、问题归类:属于Top K问题。解决方法:快速排序或者建立堆。一般采取建堆。
2、在遍历数组的同时,对元素进行处理。当堆的大小小于K的时候,直接插入,这里忽略重复元素;当大于等于K的时候,将堆顶元素与当前数组元素比较,如果取较大者存入堆中(如果堆顶元素较小,要先弹出堆顶元素,同时忽略重复元素)。
3、堆
最小堆
priority_queue<int,vector<int>,greater<vector<int>::value_type>> qs;//最小堆
set<int> minSet;
最大堆
priority_queue<int> qb;//默认最大堆
std::set<int,std::greater<int>> intSet;
关于priority_queue:点击打开链接,头文件<queue>。
代码
class Solution {
public:
int thirdMax(vector<int>& nums) {
set<int> minSet;
const int k=3, sz=nums.size();
//排除特殊情况
if(sz==0)
{
return 0;
}
if(sz==1)
{
return nums[0];
}
if(sz==2)
{
//没有第三大就返回最大
return (nums[0]>nums[1]?nums[0]:nums[1]);
}
for(const auto &im:nums)
{
if(minSet.size()<k)
{
minSet.insert(im);
}
else
{
auto iter=minSet.begin();
//记得判断该数是否已存在于最小堆
if(im>*iter&&minSet.find(im)==minSet.end())
{
minSet.erase(iter);
minSet.insert(im);
}
}
}
if(minSet.size()==3)
{
return *(minSet.begin());
}
else//没有第三大就返回最大
{
return *(minSet.rbegin());
}
}
};
结果
~很明显,我等功力还不够~