LeetCode 347 Top K Frequent Elements
题目描述
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
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.
一句话题意
求出数组中出现频率最高的k个数。
解题思路
首先遍历数组,统计每个数字的出现次数,并将对应数字的出现次数保存在HashMap中。
然后将map中的值排序,输出最大的k个数即可
0 条评论