weixin_44763375 2021-09-09 12:12 采纳率: 75%
浏览 30

LeetCode692题,对堆的比较器代码有所不解

题目如下:
Given an array of strings words and an integer k, return the k most frequent strings.

Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.



```java

![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/62286606113611.png "=600 #left")
String[] words = {"i","love","leetcode","i","love","coding"};
    int k = 2;
    List<String> res = topKFrequent(words, k);
    System.out.println(res);
}
public static List<String> topKFrequent(String[] words, int k) {
    HashMap<String, Integer> mapping = new HashMap<>();
    for(String word: words){
        if(!mapping.containsKey(word)) {
            mapping.put(word, 0);
        }
        int count = mapping.get(word) + 1;
        mapping.put(word,count);
    }
    PriorityQueue<String> pq = new PriorityQueue<>((w1, w2) -> mapping.get(w1).equals(mapping.get(w2)) ?                                                               w2.compareTo(w1): mapping.get(w1) - mapping.get(w2));
    for(String word: mapping.keySet()){
        pq.add(word);
        if(pq.size() > k){
            pq.poll();
        }
    }
    List<String> res = new ArrayList<>();
    while(!pq.isEmpty()){
        res.add(pq.poll());
    }
    Collections.reverse(res);
    return res;

我想问这一行代码
  PriorityQueue<String> pq = new PriorityQueue<>((w1, w2) -> mapping.get(w1).equals(mapping.get(w2)) ?                                                               w2.compareTo(w1): mapping.get(w1) - mapping.get(w2));
是什么意思?
  • 写回答

1条回答 默认 最新

  • 技术专家团-1001 2021-09-09 13:09
    关注

    PriorityQueue<>这个类有一个需要实现的抽象方法,有2个参数。->前后是个lambda表达式的意思,也就是对这个方法的实现

    评论

报告相同问题?

问题事件

  • 创建了问题 9月9日

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向