leetcode 692. Top K Frequent Words

目录

一、问题描述

二、代码实现

1、堆

2、排序


 

https://leetcode.com/problems/top-k-frequent-words/

给定一个单词列表,返回前k个出现频率最高的单词的列表。

 

一、问题描述

测试用例:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.

返回的列表中从左到右单词的频率依次递减,出现频率相同的单词则字典序在前面的靠前。

输入的单词均只有小写字母;输入的k合法,满足1<=k<=不同单词的数量。

要求时间O(nlogk),空间O(n)。

 

二、代码实现

1、堆

class Solution { 
    //堆
    public List<String> topKFrequent2(String[] words, int k) {
        
        Map<String, Integer> map = new HashMap<>();
        for (int i=0; i<words.length; i++) {
            if (map.containsKey(words[i]))
                map.put(words[i], map.get(words[i])+1);
            else
                map.put(words[i], 1);
        }
        
        //这里用a.getValue()==b.getValue()可能不太对,==只能在整数为-128-127之间才可以使用,应该使用a.getValue().equals(b.getValue())
        //这里用b.getKey().compareTo(a.getKey())是为了让字典序越靠后的单词处在小顶堆的更高处,比如,"abc","abd","bun",小顶堆中的删除顺序应该为"bob","bun","ban".
        //这里用a.getValue()-b.getValue()是为了定义优先队列为小顶堆,频率越小的单词处在堆的更高处
        PriorityQueue<Map.Entry<String, Integer>> heap = new PriorityQueue<>(
            (a,b) -> a.getValue()==b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue()-b.getValue()
        );
        /*
        PriorityQueue
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值