高级农民
- 积分
- 1016
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-6-13
- 最后登录
- 1970-1-1
|
贴一个第一题C++的解答。如果有bug还请指正。如果觉得有帮助,还请点赞加点米。谢谢大家。
[hide=130]
- #include <iostream>
- #include <bits/stdc++.h>
- class CSolution
- {
- int K;
- set<pair<int,int>> Set; // ordered {freq, key}
- unordered_map<int,int>Map; // key->freq
-
- public:
- void add(int key, int freq);
- void printTopK();
- CSolution(int _K) { K = _K;}
- };
- void CSolution::add(int key, int freq)
- {
- if (Set.find({Map[key],key})==Set.end())
- {
- Map[key] += freq;
- Set.insert({Map[key],key});
- if (Set.size()>K)
- Set.erase(Set.begin());
- }
- else
- {
- auto iter = Set.find({Map[key],key});
- Set.erase(iter);
- Map[key]+=freq;
- Set.insert({Map[key],key});
- }
- }
- void CSolution::printTopK()
- {
- for (auto a: Set)
- {
- cout<<"[freq "<<a.first<<", key "<<a.second<<"] ";
- }
- cout<<endl;
- }
- int main()
- {
- CSolution solution(3);
- solution.add(1,2);
- solution.add(2,3);
- solution.printTopK();
- solution.add(3,4);
- solution.add(4,5);
- solution.printTopK();
-
- solution.add(1,8);
- solution.add(5,9);
- solution.printTopK();
- solution.add(2,1);
- solution.printTopK();
- }
复制代码
[\hide] |
|