[LeetCode]414. Third Maximum Number
程序员文章站
2022-03-07 19:45:25
...
[LeetCode]414. Third Maximum Number
题目描述
思路
map可解,开始的思路是o(n)空间
参考答案,可以用o(1)空间的解法
代码
#include <iostream>
#include <map>
#include <set>
#include <vector>
using namespace std;
class Solution {
public:
int thirdMax(vector<int>& nums) {
/*
map<int, int> m;
for (int num : nums)
m[num]++;
int cur_count = 3;
for (auto iter = m.rbegin(); iter != m.rend(); iter++) {
cur_count--;
if (cur_count == 0) return iter->first;
}
if (cur_count > 0)
return m.rbegin()->first;
*/
set<int> s;
for (int num : nums) {
s.insert(num);
if (s.size() > 3) s.erase(s.begin());
}
return s.size() == 3 ? *s.begin() : *s.rbegin();
}
};
int main() {
vector<int> nums = { 3, 2,2,2,2,2, 1 };
Solution s;
cout << s.thirdMax(nums) << endl;
system("pause");
return 0;
}
下一篇: .NET Core中反解ObjectId
推荐阅读
-
Leetcode 1456. Maximum Number of Vowels in a Substring of Given Length (python)
-
【Leetcode】1072. Flip Columns For Maximum Number of Equal Rows(异或运算)
-
#leetcode#321.Create Maximum Number
-
Leetcode 321. Create Maximum Number
-
【Leetcode】414.Third Maximum Number
-
[LeetCode]414. Third Maximum Number
-
414. Third Maximum Number
-
【Array-easy】414. Third Maximum Number 找到数组中第三大的数
-
414. Third Maximum Number
-
[email protected]_414_Third_Maximum_Number