Created
November 21, 2022 03:00
-
-
Save omargfh/3adc95c46cd6471de8c0a91b1da9c1a5 to your computer and use it in GitHub Desktop.
Runtime 79 ms Beats 97.77%
This file contains 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
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