347. Top K Frequent Elements #
Problem #
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.
Problem Summary #
Given a non-empty array, output the top K elements with the highest frequency.
Solution Approach #
This problem tests priority queues. Construct the array into a priority queue, then output the top K elements.
Code #
package leetcode
import "container/heap"
func topKFrequent(nums []int, k int) []int {
m := make(map[int]int)
for _, n := range nums {
m[n]++
}
q := PriorityQueue{}
for key, count := range m {
heap.Push(&q, &Item{key: key, count: count})
}
var result []int
for len(result) < k {
item := heap.Pop(&q).(*Item)
result = append(result, item.key)
}
return result
}
// Item define
type Item struct {
key int
count int
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
// Note: because heap in golang is organized as a min-heap by default, the larger the count, the smaller Less() is, and the closer it is to the top of the heap. Here > is used to make it a max-heap
return pq[i].count > pq[j].count
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
// Push define
func (pq *PriorityQueue) Push(x interface{}) {
item := x.(*Item)
*pq = append(*pq, item)
}
// Pop define
func (pq *PriorityQueue) Pop() interface{} {
n := len(*pq)
item := (*pq)[n-1]
*pq = (*pq)[:n-1]
return item
}