微软笔试题 统计英文电子书中出现次数最多的k个单词
2014-04-03 23:40
441 查看
在v_JULY_v的文章中找到了这个问题的解法后用C++实现了一下,发现C++的代码非常的简洁。
主要用到了标准库中的hash_map,优先级队列priority_queue。
算法的思路是:
从头到尾遍历文件,从文件中读取遍历到的每一个单词。
把遍历到的单词放到hash_map中,并统计这个单词出现的次数。
遍历hash_map,将遍历到的单词的出现次数放到优先级队列中。
当优先级队列的元素个数超过k个时就把元素级别最低的那个元素从队列中取出,这样始终保持队列的元素是k个。
遍历完hash_map,则队列中就剩下了出现次数最多的那k个元素。
具体实现和结果如下:
//出现次数最多的是个单词
[cpp]
view plaincopy
//出现次数最多的是个单词
void top_k_words()
{
timer t;
ifstream fin;
fin.open("modern c.txt");
if (!fin)
{
cout<<"can nont open file"<<endl;
}
string s;
hash_map<string,int> countwords;
while (true)
{
fin>>s;
if (fin.eof())
{
break;
}
countwords[s]++;
}
cout<<"单词总数 (重复的不计数):"<<countwords.size()<<endl;
priority_queue<pair<int,string>,vector<pair<int,string>>,greater<pair<int,string>>> countmax;
for(hash_map<string,int>::const_iterator i=countwords.begin();
i!=countwords.end();i++)
{
countmax.push(make_pair(i->second,i->first));
if (countmax.size()>10)
{
countmax.pop();
}
}
while(!countmax.empty())
{
cout<<countmax.top().second<<" "<<countmax.top().first<<endl;
countmax.pop();
}
cout<<"time elapsed "<<t.elapsed()<<endl;
}
![](http://my.csdn.net/uploads/201207/22/1342930189_6510.png)
主要用到了标准库中的hash_map,优先级队列priority_queue。
算法的思路是:
从头到尾遍历文件,从文件中读取遍历到的每一个单词。
把遍历到的单词放到hash_map中,并统计这个单词出现的次数。
遍历hash_map,将遍历到的单词的出现次数放到优先级队列中。
当优先级队列的元素个数超过k个时就把元素级别最低的那个元素从队列中取出,这样始终保持队列的元素是k个。
遍历完hash_map,则队列中就剩下了出现次数最多的那k个元素。
具体实现和结果如下:
//出现次数最多的是个单词
[cpp]
view plaincopy
//出现次数最多的是个单词
void top_k_words()
{
timer t;
ifstream fin;
fin.open("modern c.txt");
if (!fin)
{
cout<<"can nont open file"<<endl;
}
string s;
hash_map<string,int> countwords;
while (true)
{
fin>>s;
if (fin.eof())
{
break;
}
countwords[s]++;
}
cout<<"单词总数 (重复的不计数):"<<countwords.size()<<endl;
priority_queue<pair<int,string>,vector<pair<int,string>>,greater<pair<int,string>>> countmax;
for(hash_map<string,int>::const_iterator i=countwords.begin();
i!=countwords.end();i++)
{
countmax.push(make_pair(i->second,i->first));
if (countmax.size()>10)
{
countmax.pop();
}
}
while(!countmax.empty())
{
cout<<countmax.top().second<<" "<<countmax.top().first<<endl;
countmax.pop();
}
cout<<"time elapsed "<<t.elapsed()<<endl;
}
![](http://my.csdn.net/uploads/201207/22/1342930189_6510.png)
![](http://my.csdn.net/uploads/201207/24/1343100878_4090.png)
相关文章推荐
- TOP K算法(微软笔试题 统计英文电子书中出现次数最多的k个单词)
- 微软笔试题 统计英文电子书中出现次数最多的k个单词
- JAVA-统计英文句子中出现次数最多的单词和出现的次数
- 统计一篇英文文章中出现次数最多的前五个单词
- Java统计一篇文章中出现次数最多的汉字或英文单词 又出现次数的统计
- 转载:统计一串英文中出现次数最多的单词以及次数;
- Java统计英文句子中出现次数最多的单词并计算出现次数的方法
- F# 统计一段英文文章中不同单词出现的次数
- 一个笔试面试经常问的问题——统计字符串中出现最多的字符及次数
- Java统计一篇英文单词出现次数
- 用C语言实现了对英文文章中单词频率的统计,得到出现最多的前十个!
- sort +awk+uniq 统计文件中出现次数最多的前10个单词
- (转)F# 统计一段英文文章中不同单词出现的次数
- 统计英文单词的出现次数
- 统计一串字符串中出现次数最多和次多的单词
- 统计英文文件中单词数和各单词出现的频率(次数)
- Java 读取一段英文文档统计每个单词出现的次数和单词的总数
- 黑马程序员——统计文件中每个英文单词出现的次数
- 统计出现次数最多的单词
- C# 实现统计字符串中不同单词的出现次数【百度笔试题】