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.
給定一非空整數(shù)數(shù)組,返回其第三小的元素退渗,若不存在則返回最大的數(shù)脆炎。算法時間控制在O(n)。這里重復(fù)的數(shù)字視為一個氓辣。
思路
一般選擇問題,選第三大袱蚓。
直接進(jìn)行掃描钞啸,記錄第三大或最大的做法存在如下錯誤:當(dāng)若使用int型變量記錄元素,當(dāng)?shù)谌笄『脼镮NT_MIN時將出現(xiàn)錯誤喇潘,因?yàn)闊o法判定這里的INT_MIN是掃描出的第三大還是沒找到第三大而留下的變量初值体斩。
正確的做法是使用set,利用set元素排列有序的特性颖低。
class Solution {
public:
int thirdMax(vector<int>& nums) {
set<int> top3;
for (int num : nums) {
top3.insert(num);
if (top3.size() > 3)
top3.erase(top3.begin());
}
return top3.size() == 3 ? *top3.begin() : *top3.rbegin();
}
};