题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
using psi = pair<string, int>; // 自定义大顶堆 struct cmp { bool operator()(const psi& p1, const psi& p2) { if (p1.second != p2.second) return p1.second < p2.second; return p1.first > p2.first; } }; vector<vector<string> > topKstrings(vector<string>& strings, int k) { vector<vector<string> > ans; int len = strings.size(); if (len == 0) return ans; unordered_map<string, int> umap; for (const auto& s : strings) { ++umap[s]; } priority_queue<psi, vector<psi>, cmp> pque(umap.begin(), umap.end()); // 取大顶堆前k元素 while (k-- && !pque.empty()) { auto tmp = pque.top(); pque.pop(); ans.emplace_back(vector<string>{ tmp.first, to_string(tmp.second) }); } return ans; } int main() { vector<string> vec{ "123","123","231","32" }; auto ans = topKstrings(vec, 2); return 0; }