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.
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.
本提题意就是寻找第三大的数据,这里我们使用一个set来表示,注意set是一个高度平衡的二叉搜索树,所以注意set数据结构的使用
set–常见成员函数及基本用法
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <bitset>
using namespace std;
class Solution
{
public:
int thirdMax(vector<int>& nums)
{
set<int> ss;
for (int i : nums)
{
ss.insert(i);
if (ss.size() > 3)
ss.erase(ss.begin());
}
if(ss.size()==3)
return *(ss.begin());
else
return *(ss.rbegin());
}
};