-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtopKFrequent.go
More file actions
43 lines (31 loc) · 867 Bytes
/
Copy pathtopKFrequent.go
File metadata and controls
43 lines (31 loc) · 867 Bytes
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
/* https://leetcode.com/problems/top-k-frequent-elements/
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
*/
package larray
import (
pq "github.com/TTWShell/algorithms/data-structure/priority-queue"
)
func topKFrequent(nums []int, k int) []int {
countMaps := map[int]int{}
for _, num := range nums {
countMaps[num]++
}
pQueue := pq.PQConstructor()
for k, v := range countMaps {
pQueue.Insert(pq.Element{Value: k, Priority: v})
}
res := make([]int, k)
for i := range res {
res[i] = pQueue.Extract().Value.(int)
}
return res
}