LeetCode - Top K Frequent Words

本文详细解析了一种高效求解Top K频繁元素的算法,通过使用HashMap存储字符串及其频率,再利用大小为K的优先队列进行排序和筛选,最终返回按频率和字母顺序排列的前K个最频繁元素。该算法适用于大数据集,尝试在O(nlogk)时间内解决,并保持O(n)额外空间复杂度。
Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:
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.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.
Follow up:
Try to solve it in O(n log k) time and O(n) extra space.

  先用 hashmap 存储string 和出现次数的映射, 然后insert并维持一个size为K的priorityqueue (注意要自己定义compare 函数),最后会得到top Kth words 但是是从小到大排序,注意要reverse:

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        if(words == null || words.length == 0 || k <= 0){
            return new ArrayList<String>();
        }
        Map<String, Integer> map = new HashMap<>();
        PriorityQueue<Map.Entry<String,Integer>> pq = new PriorityQueue<>((e1, e2) -> compareElement(e1,e2));
        for(String str : words){
            map.put(str, map.getOrDefault(str, 0)+1);
        }
        for(Map.Entry<String,Integer> entry : map.entrySet()){
            pq.add(entry);
            if(pq.size() > k){
                pq.poll();
            }
        }
        List<String> res = new ArrayList<>();
        while(!pq.isEmpty()){
            res.add(pq.poll().getKey());
        }
        Collections.reverse(res);
        return res;
    }
    
    private int compareElement(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2){
        if(e1.getValue() - e2.getValue() != 0) 
            {return e1.getValue() - e2.getValue();} 
        else
            {return e2.getKey().compareTo(e1.getKey());}
    }
}

  

转载于:https://www.cnblogs.com/incrediblechangshuo/p/9694614.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值