414.Third Maximum Number
414.Third Maximum Number
难度:Easy
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).
1
Example 1:
2
Input: [3, 2, 1]
3
4
Output: 1
5
6
Explanation: The third maximum is 1.
7
Example 2:
8
Input: [1, 2]
9
10
Output: 2
11
12
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
13
Example 3:
14
Input: [2, 2, 3, 1]
15
16
Output: 1
17
18
Explanation: Note that the third maximum here means the third maximum distinct number.
19
Both numbers with value 2 are both considered as second maximum.
Copied!
topK用最小堆,去重用set。
1
class Solution {
2
public:
3
int thirdMax(vector<int>& nums) {
4
if(nums.size()<3) return *max_element(nums.begin(),nums.end());
5
priority_queue<int,vector<int>,greater<int>>three;
6
unordered_set<int>ele;
7
8
for(int i=0;i<nums.size();i++)
9
{
10
if(ele.count(nums[i])) continue;
11
three.push(nums[i]);
12
ele.insert(nums[i]);
13
}
14
if(three.size()==1) return three.top();
15
if(three.size()==2) {three.pop(); return three.top();}
16
while(three.size() !=3) three.pop();
17
return three.top();
18
19
}
20
};
Copied!
执行用时 :24 ms, 在所有 C++ 提交中击败了13.20%的用户 内存消耗 :10.8 MB, 在所有 C++ 提交中击败了5.05%的用户
Copy link