C++のトップKのよくある単語
これを解決するには、次の手順に従います-
- mと呼ばれる1つのマップを定義します
- 優先キューを1つ作成するv
- for i:=0 to n、ここでnは単語配列のサイズであり、m[words[i]]を1増やします
- マップ内の各要素eについて
- サイズがv
- それ以外の場合、v.topの値が
- それ以外の場合、v.topの値が=eの値であり、v.topのキーが> eのキーである場合、vから最上位の要素を削除し、eをvに挿入します
- それ以外の場合、v.topの値が
- サイズがv
- resと呼ばれる1つの配列を定義します
- vが空でない間、
- temp:=vのトップ
- vからトップを削除
- tempのキーをres配列に挿入します
- res配列を逆にする
- return res
理解を深めるために、次の実装を見てみましょう-
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
struct Comparator{
bool operator()(pair <string ,int> a, pair <string, int> b){
if(a.second != b.second) return !(a.second < b.second);
return !(a.first > b.first);
}
};
class Solution {
public:
static bool cmp(pair <string, int> a, pair <string, int> b){
if(a.second != b.second) return a.second > b.second;;
return a.first < b.first;
}
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> m;
priority_queue < pair <string, int>, vector < pair <string, int> >, Comparator > v;
for(int i = 0; i < words.size(); i++){
m[words[i]]++;
}
map<string, int> :: iterator i = m.begin();
while(i != m.end()){
if(v.size() < k){
v.push(*i);
}
else if(v.top().second < i->second){
v.pop();
v.push(*i);
}
else if(v.top().second == i->second && v.top().first > i->first){
v.pop();
v.push(*i);
}
i++;
}
vector <string> res;
while(!v.empty()){
pair <string, int> temp = v.top();
v.pop();
res.push_back(temp.first);
}
reverse(res.begin(), res.end());
return res;
}
};
main(){
Solution ob;
vector<string> v = {"the", "sky", "is", "blue", "the", "weather", "is", "comfortable"};
print_vector(ob.topKFrequent(v, 3));
} 入力
["the", "sky", "is", "blue", "the", "weather", "is", "comfortable"] 3
出力
["is","the","blue"]
-
Window上のc++のトップIDEは何ですか?
大きなプロジェクトは、単なるテキストエディタでは管理が困難です。このような場合にIDEを使用すると、生産性が向上し、フラストレーションが軽減される可能性があります。 IDEにはさまざまな種類があり、ニーズに合ったものを選択する必要があります。これがWindowに最適なC/C++IDEのリストです。 Visual Studio − Microsoftが開発したIDEです。このIDEは、Windows上でC ++のプログラムを構築、開発、およびプロファイリングするためのクラス最高のツールを備えています。 Visual Studioには、多数のプラグインを備えた巨大なプラグインストアもありま
-
PythonのトップKの頻繁な要素
空でない整数の配列があるとします。 k番目に頻度の高い要素を返す必要があります。したがって、要素が[1,1,1,1,2,2,3,3,3]でk =2の場合、結果は次のようになります 正式には、関数は- i、j、kが存在する場合はtrueを返します 0≤i