列表

详情


692. 前K个高频单词

给定一个单词列表 words 和一个整数 k ,返回前 k 个出现次数最多的单词。

返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率, 按字典顺序 排序。

 

示例 1:

输入: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
    注意,按字母顺序 "i" 在 "love" 之前。

示例 2:

输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
    出现次数依次为 4, 3, 2 和 1 次。

 

注意:

 

进阶:尝试以 O(n log k) 时间复杂度和 O(n) 空间复杂度解决。

相似题目

前 K 个高频元素

最接近原点的 K 个点

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: vector<string> topKFrequent(vector<string>& words, int k) { } };

python3 解法, 执行用时: 40 ms, 内存消耗: 15 MB, 提交时间: 2022-07-21 10:29:08

class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        c = collections.Counter(words)
        res = sorted(c, key=lambda word:(-c[word], word))
        return res[:k]

golang 解法, 执行用时: 8 ms, 内存消耗: 4.3 MB, 提交时间: 2021-06-02 11:19:13

func topKFrequent(words []string, k int) []string {
    ans := []string{}
    m := map[string]int{}
    for _, word := range words {
        m[word]++
    }
    for w := range m {
        ans = append(ans, w)
    }
    
    sort.Slice(ans, func(i, j int) bool {
        s, t := ans[i], ans[j]
        return m[s] > m[t] || m[s] == m[t] && s < t
    })
    return ans[:k]
}

上一题

下一题