代码拉取完成,页面将自动刷新
//
// 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
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。