前k个高频元素
题目描述
给你一个整数数组nums
和一个整数k
,请你返回其中出现频率前k
高的元素。你可以按任意顺序返回答案。
示例 1:
1
2
|
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
|
示例 2:
1
2
|
输入: nums = [1], k = 1
输出: [1]
|
思路
题目要求
- 给定一个数组和一个整数k
- 返回数组中出现频率前k高的元素
分两步
注意
- 用
map
统计数字出现的频率
- 用
sort
包函数对频率进行快排
代码
Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
func topKFrequent(nums []int, k int) []int {
maphash := make(map[int]int)
for _, value := range nums {
// 统计频率
maphash[value]++
}
// 取出去重的数字,即字典的key
keys := make([]int, 0)
for key, _ := range maphash {
keys = append(keys, key)
}
// 按频率对数字排序,即按value对key排序
sort.Slice(keys, func(i, j int) bool {
// 排序规则(降序)
return maphash[keys[i]] > maphash[keys[j]]
})
// 返回频率前k高的数字
return keys[:k]
}
|
Link
GitHub