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.
求一个数组中第3大的数,如果不存在第3大的数,则返回最大的数。用set可以实现。遍历数组,将数组元素插入set,并保持set大小为3,如果超过3,就删除set的第一项(最小的)。最后如果set的大小是3的话说明有第3大的数,返回set的第一项;否则的话返回set的最后一项。
代码:
class Solution
{
public:
int thirdMax(vector<int>& nums)
{
set<int> big3;
for(auto num:nums)
{
big3.insert(num);
if(big3.size() > 3)
{
big3.erase(big3.begin());
}
}
return big3.size() == 3 ? *big3.begin() : *big3.rbegin();
}
};