Skip to content

Instantly share code, notes, and snippets.

@omargfh
Created November 21, 2022 03:00
Show Gist options
  • Save omargfh/3adc95c46cd6471de8c0a91b1da9c1a5 to your computer and use it in GitHub Desktop.
Save omargfh/3adc95c46cd6471de8c0a91b1da9c1a5 to your computer and use it in GitHub Desktop.
Runtime 79 ms Beats 97.77%
function topKFrequent(nums: number[], k: number): number[] {
let map = new Map<number, number>();
for (const num of nums) {
if (map.has(num)) {
map.set(num, map.get(num) + 1);
}
else {
map.set(num, 1);
}
}
return [...map.keys()].sort((a: number, b: number) => {
a = map.get(a);
b = map.get(b);
return a > b ? -1 : b < a ? 1 : 0;
}).slice(0, k);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment