4
LeetCode 第347题 Top K Frequent Elements
source link: https://codechina.org/2019/08/leetcode-347-top-k-frequent-elements/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
来源:https://leetcode.com/problems/top-k-frequent-elements/
题目:前K个最频繁的元素
给定一个非空的数字数组,返回前K个最频繁的元素。
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:
- 你可以假定k永远是合法的,1 ≤ k ≤ 不重复的数字数。
- 算法时间复杂度应该好于O(n log n),n为数组的尺寸。
用hashmap复杂度不会高。我们其实就是用hashmap来统计每个数字的出现频度。然后把这个统计信息转换成一个列表,然后排序,然后输出前k个结果即可。
Github: https://github.com/tinyfool/leetcode/tree/master/src/p0347
本题属于哈希表类题目,想了解更多关于哈希表的题目,可以参看哈希表专题。
此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK