LeetCode 692. 前K个高频单词

题目描述

692. 前 K 个高频单词

image-20250420085905359

思路分析

小顶堆

image-20250508024726325

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
type WordItem struct {
	word string
	freq int
}

// 定义一个最小堆
type MinHeap []WordItem

func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool {
	if h[i].freq == h[j].freq {
		return h[i].word > h[j].word // 字典序较大的排在后面
	}
	return h[i].freq < h[j].freq
}
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }

func (h *MinHeap) Push(x interface{}) {
	*h = append(*h, x.(WordItem))
}

func (h *MinHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func topKFrequent(words []string, k int) []string {
	// 统计频率
	freqMap := make(map[string]int)
	for _, word := range words {
		freqMap[word]++
	}

	// 使用最小堆
	h := &MinHeap{}
	heap.Init(h)

	for word, freq := range freqMap {
		heap.Push(h, WordItem{word, freq})
		if h.Len() > k {
			heap.Pop(h)
		}
	}

	res := make([]string, 0, k)
	for h.Len() > 0 {
		res = append(res, heap.Pop(h).(WordItem).word)
	}

	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}
  • 时间复杂度:O (n log k),其中 n 是单词的数量。

    我们需要遍历单词并将每个单词插入堆中,堆的操作时间复杂度为 O (log k)。

  • 空间复杂度:O (n),用于存储频率哈希表和堆。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/74023962
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!