1 Star 0 Fork 0

luobg01/PFJ_coding

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
code032_topK.h 2.32 KB
一键复制 编辑 原始数据 按行查看 历史
luobg01 提交于 2023-12-10 13:51 . 新增题目 topk
//
// Created by 罗炳国 on 2023/11/24.
//
#ifndef PFJ_CODE032_TOPK_H
#define PFJ_CODE032_TOPK_H
#include "commonHeader.h"
// topK问题
/**
* Top K Frequent Words II
* Implement three methods for Topk Class:
* TopK(k). The constructor.
* add(word). Add a new word.
* topk(). Get the current top k frequent words.
* LintCode题目:https://www.lintcode.com/problem/550/
* */
class code032_topK {
public:
code032_topK(int K) {
this->k = K;
}
void add(string &str) {
auto iter = strNodeMap.find(str);
if (iter == strNodeMap.end()) {
strNodeMap[str] = new Node(str, 1);
}
}
vector<string> topK() {
vector<string> ans;
return ans;
}
private:
struct Node {
string str;
int times;
Node(string &str, int times) : str(str), times(times) {
}
};
struct dataCmp {
bool operator() (const struct Node * &a, const struct Node *&b) {
if (a->times > b->times)
return true;
if (a->times == b->times)
return a->str.compare(b->str) < 0;
return false;
}
};
struct dataCmp1 {
bool operator() (const struct Node &a, const struct Node &b) {
if (a.times > b.times)
return true;
if (a.times == b.times)
return a.str.compare(b.str) < 0;
return false;
}
};
bool dataItemCmp(struct Node *a, struct Node *b) {
if (a->times > b->times)
return true;
if (a->times == b->times)
return a->str.compare(b->str) < 0;
return false;
}
private:
// 堆使用,记录节点与索引下标
unordered_map<struct Node *, int> nodeIndex;
// 优化项,记录当前位于堆中的节点
set<struct Node , struct dataCmp1> treeSet;
// 记录 string与内部的节点之间的关系,利用这个关系更新词频
unordered_map<string, struct Node *> strNodeMap;
// 初始化即固定的参数K
int k;
};
void topKtest() {
class code032_topK tk(2);
vector<string> strs {"a", "b", "fd", "fd", "gh", "jk", "gh", "jk", "jk", "gh"};
vector<string> ans;
for (auto &str : strs) {
tk.add(str);
ans = tk.topK();
vecShow(ans);
}
}
#endif//PFJ_CODE032_TOPK_H
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/luobg01/pfj_coding.git
git@gitee.com:luobg01/pfj_coding.git
luobg01
pfj_coding
PFJ_coding
master

搜索帮助