作者:小 琛
欢迎转载,请标明出处
topK问题的由来
生活中,经常性的会有如下场景:现有M总数的东西,其中各个元素的数量不等,从这M个东西中提取数量为前K个的东西来。
例如:
topK问题的解决
分析:该问题最棘手的点在于,在M个东西中,其每个元素的数量并不是唯一的,比如例题中,这些单词的数量确定,但“i”的数量为2,“love”的数量为2。也就是说,我们需要考虑的变量有两个:元素本身、数量。
这里就要用STL中的关联性容器解决即:map。
解例题
- 首先,巧妙利用map,将map设定为map<string,int>,string为元素本身,int用来统计该元素的数量,利用map的去重性质,达到了统计效果。
map<string, int> count_map;//定义一个map,键对值为<string,int>
for (auto k : words)
{
count_map[k]++;//利用map中的[]来进行统计数量
}
- 利用步骤1统计出来的数量,进行排序。这里需要利用multimap。(因为单词有数量相同的情况,例如“i”与“love”同为2个)。这里将multimap的默认排序修改为了从大到小,便于后续的提取
multimap<int,string,greater<int> >sort_map;
for (auto kv: count_map)
{
sort_map.insert(make_pair(kv.second,kv.first));
}
- 设定一个vector< string>,遍历刚刚排序好的sort_map,寻找其中前K个元素,存入vector中。
auto it=sort_map.begin();
vector<string> s;
while (it!=sort_map.end())
{
if (k==0)
break;
s.push_back(it->second);
it++;
k--;
}
总体代码:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k)
{
map<string, int> count_map;
for (auto k : words)
{
count_map[k]++;
}
multimap<int, string, greater<int> >sort_map;
for (auto kv : count_map)
{
sort_map.insert(make_pair(kv.second, kv.first));
}
auto it = sort_map.begin();
vector<string> s;
while (it != sort_map.end())
{
if (k == 0)
break;
s.push_back(it->second);
it++;
k--;
}
return s;
}
};
总结
举一反三,通过上面的例子,要理解topK问题解决的本质。即将需要考虑的两个变量设定为关联性容器的键对值,通过关联性容器的性质统计、排序、提取。