DChalo123:
私は前に1を使用したことがないよう、優先度つきキューを使用する方法を学習しようとしています。ここでは、使用中の1の例では、私は文字列の配列でトップKの要素を見つける問題に対してLeetCode上で発見したということです
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap();
for (String word: words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2) -> count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) );
for (String word: count.keySet()) {
heap.offer(word);
if (heap.size() > k) heap.poll();
}
List<String> ans = new ArrayList();
while (!heap.isEmpty()) ans.add(heap.poll());
Collections.reverse(ans);
return ans;
}
もっととりわけ私は、この行が何をしているか知っていただきたいと思います。
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2) -> count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) );
誰かがここで何が起こっているかを足の不自由な人の言葉で説明できますか?声明「場合」の正規としてcomparaterを書き換えする方法はありますか?
任意の助けてくれてありがとう。
ricky3350:
あなたはコンストラクタを持っている表現があるラムダ式。のでComparator
、それが唯一の抽象メソッドとのインタフェースだ、ある機能のインターフェース、である、ラムダ式は、匿名クラスを作成するための省略形として使用することができます。
あなたの例では、
new PriorityQueue<String>((w1, w2) -> count.get(w1).equals(count.get(w2)) ? w2.compareTo(w1) : count.get(w1) - count.get(w2));
と機能的に同等です
new PriorityQueue<String>(new Comparator<String>() {
public int compare(String w1, String w2) {
return count.get(w1).equals(count.get(w2)) ? w2.compareTo(w1) : count.get(w1) - count.get(w2);
}
});
これはまた、実装する別のクラスを作ると同じであろうComparator<String>
、とのパラメータとして、そのクラスのインスタンスを渡しますPriorityQueue
。
書き込みに関してはComparator
if文のように、短い答えはノーです。コンパレータは、のインスタンスである必要がありますComparator<String>
。次のようにしかし、おそらく同じコンパレータのより理解しやすいバージョンは次のとおりです。
new PriorityQueue<String>((w1, w2) -> {
if (count.get(w1).equals(count.get(w2))) { // If the counts of w1 and w2 are the same,
return w2.compareTo(w1); // Then return the reverse lexicographical ordering of w1 and w2 (e.g. "Zebra" comes before "Apple")
} else if (count.get(w1) < count.get(w2)) {
return -1; // w1 comes before w2
} else {
return 1; // w1 comes after w2
}
});
注:「辞書的順序は、」基本的にアルファベット順ですが、ASCIIコードに基づきます。詳細については、String#compareTo(String)
お役に立てれば!