TOP K演算法(微軟筆試題 統計英文電子書中出現次數最多的k個單詞)
阿新 • • 發佈:2019-01-28
在v_JULY_v的文章中找到了這個問題的解法後用C++實現了一下,發現C++的程式碼非常的簡潔。
主要用到了標準庫中的hash_map,優先順序佇列priority_queue。
演算法的思路是:
- 從頭到尾遍歷檔案,從檔案中讀取遍歷到的每一個單詞。
- 把遍歷到的單詞放到hash_map中,並統計這個單詞出現的次數。
- 遍歷hash_map,將遍歷到的單詞的出現次數放到優先順序佇列中。
- 當優先順序佇列的元素個數超過k個時就把元素級別最低的那個元素從佇列中取出,這樣始終保持佇列的元素是k個。
- 遍歷完hash_map,則佇列中就剩下了出現次數最多的那k個元素。
具體實現和結果如下:
//出現次數最多的是個單詞
//出現次數最多的是個單詞 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; }