Skip to content
New issue

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

347. 前 K 个高频元素 #83

Open
webVueBlog opened this issue Sep 6, 2022 · 0 comments
Open

347. 前 K 个高频元素 #83

webVueBlog opened this issue Sep 6, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

347. 前 K 个高频元素

Description

Difficulty: 中等

Related Topics: 数组, 哈希表, 分治, 桶排序, 计数, 快速选择, 排序, 堆(优先队列)

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

输入: nums = [1], k = 1
输出: [1]

提示:

  • 1 <= nums.length <= 105
  • k 的取值范围是 [1, 数组中不相同的元素的个数]
  • 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的

**进阶:**你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n是数组大小。

Solution

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
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant