Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created July 17, 2020 08:18
Show Gist options
  • Save RP-3/b5aec8695cb04b972ae1237eff2313cc to your computer and use it in GitHub Desktop.
Save RP-3/b5aec8695cb04b972ae1237eff2313cc to your computer and use it in GitHub Desktop.
/**
* @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