MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / topKFrequent

Function topKFrequent

top_k_frequent_elements_347/solution.go:33–57  ·  view source on GitHub ↗

Time: O(n) Space: O(n)

(nums []int, k int)

Source from the content-addressed store, hash-verified

31// Time: O(n)
32// Space: O(n)
33func topKFrequent(nums []int, k int) []int {
34 // build map of frequencies
35 freq := make(map[int]int)
36 for _, n := range nums {
37 freq[n] += 1
38 }
39
40 // push frequencies into freqHeap
41 h := &freqHeap{}
42 heap.Init(h)
43 for k, v := range freq {
44 heap.Push(h, freqHeapVal{
45 key: k,
46 val: v,
47 })
48 }
49
50 // pop k largest frequency items from the freqHeap
51 top := make([]int, k)
52 for i := 0; i < k; i++ {
53 top[i] = heap.Pop(h).(freqHeapVal).key
54 }
55
56 return top
57}

Callers 1

Test_topKFrequentFunction · 0.85

Calls 2

PushMethod · 0.45
PopMethod · 0.45

Tested by 1

Test_topKFrequentFunction · 0.68