Created
July 17, 2020 08:18
-
-
Save RP-3/b5aec8695cb04b972ae1237eff2313cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @param {number} k | |
* @return {number[]} | |
*/ | |
var topKFrequent = function(nums, k) { | |
const counter = new Map(); | |
nums.forEach((n) => { | |
if(!counter.has(n)) counter.set(n, 1); | |
else counter.set(n, counter.get(n) + 1); | |
}); | |
const counts = new Array(nums.length+1).fill(0).map(() => []); | |
for(let [num, count] of counter) counts[count].push(num); | |
const result = []; | |
for(let i=counts.length-1; i>=0 && result.length < k; i--){ | |
result.push(...counts[i]); | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment