# LeetCode-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: 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, 2, 1]

输入: [1, 2]

输入: [2, 2, 3, 1]

Method1：

Method 2：

LeetCode上有人是这样做的，很巧妙，因为重复的数字算作同一个，因此，用一个有序的集合set来存储数字，而且，整个set中最多只存储3个数字，那么如果set的个数为3，那么set.begin()即是第三大的数字；若set中的数字少于3，也就是不存在第三大的数字，那么s.rbegin()（反向迭代器）中就是最大的数字。

C++代码（Visual Studio 2017）：

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;

class Solution {
public:
int thirdMax(vector<int>& nums) {
//Method 1:
set<int> s;
sort(nums.begin(), nums.end());
for (int num : nums) {
s.insert(num);
}
if (s.size() < 3)
return *s.rbegin();
int count = 0;
for (set<int>::iterator it = s.begin(); it != s.end(); it++) {
count++;
if (count == s.size() - 2)
return *it;
}

/*Method 2:
set<int> top3;
for (int num : nums) {
top3.insert(num);
if (top3.size() > 3)
top3.erase(top3.begin());
}
}
};

int main()
{
Solution s;
vector<int> nums = { 3,2,2,1 };
int result;
result = s.thirdMax(nums);
cout << result;
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120