上千万或上亿的数据,现在的机器的内存应该能存下。所以考虑采用hash_map/搜索二叉树/红黑树等来进行统计次数。然后就是取出前N个出现次数最多的数据了,可以用第2题提到的堆机制完成。
#include "IOSTREAM"
#include<hash_map>
#include<string>
#include<map>
using namespace std;
int main(void)
{
//海量待统计数据
char* a[5]={"ab","b","ccc","ab","ccc"};
//哈希映射统计频率
hash_map<char *,int> hp;
for(int i=0;i<5;i++)
{
if(hp.find(a[i])!=hp.end())
{
hp[a[i]]++;
}
else
{
hp[a[i]]=1;
}
}
//对字符串按出现频率排序
multimap<int,char*> m;
hash_map<char*,int>::iterator it;
for(it=hp.begin();it!=hp.end();it++)
m.insert(pair<int,char*>(it->second,it->first));
//输出出现频率最高的两个字符串
multimap<int,char*>::iterator t=m.end();
for(int i=1;i<=2;i++)
{
t--;
cout<<t->second<<endl;
}
}
上千万或上亿数据(有重复),统计其中出现次数最多的N个数据. C++实现
原文地址:http://blog.csdn.net/u013011841/article/details/44249351