道阻且长,行则将至,走慢一点没关系,不停下|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2023-12-17 11:04阅读: 3评论: 0推荐: 0

[LeetCode] LeetCode692. 前K个高频单词

题目描述

思路

注意是前K个高频单词,就是TopK问题,只能用小根堆找最大的K个元素啊,用大根堆找的就是最小的K个元素了

思路一:

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>();
        // 小顶堆
        PriorityQueue<Map.Entry<String, Integer> > heap = new PriorityQueue<>(
            (s1, s2) -> {
                if (s1.getValue().equals(s2.getValue())) {
                    return s2.getKey().compareTo(s1.getKey());
                } else {
                    return s1.getValue() - s2.getValue();
                }
            }
        );
        List<String> res = new ArrayList<>();
        for (String str : words) {
            map.put(str, map.getOrDefault(str, 0) + 1);
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            heap.add(entry);
            if (heap.size() > k) {
                heap.remove();
            }
        }
        while (!heap.isEmpty()) {
            res.add(heap.remove().getKey());
        }

        Collections.reverse(res);
        return res;
    }
}

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/17908869.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(3)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.