We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difficulty: 中等
Related Topics: 数组, 哈希表, 分治, 桶排序, 计数, 快速选择, 排序, 堆(优先队列)
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
nums
k
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2]
示例 2:
输入: nums = [1], k = 1 输出: [1]
提示:
[1, 数组中不相同的元素的个数]
**进阶:**你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n是数组大小。
O(n log n)
n
Language: JavaScript
/** * @param {number[]} nums * @param {number} k * @return {number[]} */ var topKFrequent = function(nums, k) { let arr = [...new Set(nums)] // 数组去重,获取元素 let count = 0 // 次数 let rest = [] let m = new Map() // 存储元素及其对应的次数 for (let i = 0; i < arr.length; i++) { // 遍历数组中 的每个元素 不重复的arr nums.forEach(element => { if (element === arr[i]) { count++ } }) m.set(arr[i], count) // 存储 count = 0 // 重置 } let arr2 = Array.from(m) // Map => Array arr2.sort((a, b) => { return b[1] - a[1] }) // 按出现次数降序排列 for (let i = 0; i < k; i++) { // 返回前k个元素 rest.push(arr2[i][0]) } return rest };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
347. 前 K 个高频元素
Description
Difficulty: 中等
Related Topics: 数组, 哈希表, 分治, 桶排序, 计数, 快速选择, 排序, 堆(优先队列)
给你一个整数数组
nums
和一个整数k
,请你返回其中出现频率前k
高的元素。你可以按 任意顺序 返回答案。示例 1:
示例 2:
提示:
k
的取值范围是[1, 数组中不相同的元素的个数]
k
个高频元素的集合是唯一的**进阶:**你所设计算法的时间复杂度 必须 优于
O(n log n)
,其中n
是数组大小。Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: