当前位置:网站首页>347. top k high frequency elements

347. top k high frequency elements

2022-06-11 06:21:00 Geek student

347. front K High frequency elements

Give you an array of integers nums And an integer k , Please return to the frequency before k High element . You can press In any order Return to the answer .
 Insert picture description here

It seems that the time complexity is not satisfied ,js Writing priority queues is too complicated , Wait and see

Ideas

First map once , Calculate the frequency of each number
Then arrange them in descending order of frequency Before the final election k individual

var topKFrequent = function (nums, k) {
    
    let res = [];
    const map = new Map();
    for (const num of nums) {
    
        map.set(num, (map.get(num) || 0) + 1);
    }
    //  Returns the iteration object of an array , This object contains the key value pairs of the array (key,value)
    //  In descending order of frequency 
    let sortedArray = [...map.entries()].sort((a, b) => b[1] - a[1]);

    for (let i = 0; i < k; i++) {
    
        res.push(sortedArray[i][0]);
    }
    return res;

};

Chain writing :

var topKFrequent = function (nums, k) {
    
    let res = [];
    const map = new Map();
    nums.forEach(num => map.set(num, (map.get(num) || 0) + 1));

    return [...map.entries()]
        .sort((a, b) => b[1] - a[1])
        .map(x => x[0])
        .slice(0, k);

}
原网站

版权声明
本文为[Geek student]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020527521294.html