1. 程式人生 > >上千萬或上億資料(有重複),統計其中出現次數最多的N個數據. C++實現

上千萬或上億資料(有重複),統計其中出現次數最多的N個數據. C++實現

上千萬或上億的資料,現在的機器的記憶體應該能存下。所以考慮採用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;
	}

}