1.题目
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
第三大的数是1
Example 2:
Input: [1, 2]
Output: 2
第三大的数不存在,所以返回最大值2
Example 3:
Input: [2, 2, 3, 1]
Output: 1
注意第三大的数不包括重复的数,所以第三大的数是1
2.分析
大致两种思路:
方法1: 使整个数组的元素有序,返回第三大的数。注意去重。
实现可以借助数据结构,例如c++的set
方法2:维护一个长度为k=3的数据结构,其中存放了当前遍历到的元素中前k=3大的数。这种方法可以扩展到当数组长度很大,k也很大的情况。
如果k比较大,可以考虑大根堆
此题中k=3,可以直接用三个变量分别存放前3大的数。
3.代码
方法1:
class Solution {
public:
int thirdMax(vector<int>& nums) {
set<int> seq(nums.begin(), nums.end());
set<int>::reverse_iterator it = seq.rbegin();
if (seq.size() < 3)
return *it;
else {
++it;
++it;
return *it;
}
}
};
方法2:
注意类型要用long long
class Solution {
public:
int thirdMax(vector<int>& nums) {
long long max_1 = LLONG_MIN;
long long max_2 = LLONG_MIN;
long long max_3 = LLONG_MIN;
for (auto n : nums) {
if (n == max_3 || n == max_2 || n == max_1)
continue;
else if(n > max_1) {
max_3 = max_2;
max_2 = max_1;
max_1 = n;
}
else if (n > max_2) {
max_3 = max_2;
max_2 = n;
}
else if (n > max_3)
max_3 = n;
}
return max_3 == LLONG_MIN ? max_1 : max_3;
}
};