From 860749d1af995907a80a4cf1cbd5e067e3dc8859 Mon Sep 17 00:00:00 2001 From: BangDori Date: Mon, 16 Dec 2024 19:35:41 +0900 Subject: [PATCH] Top K Frequent Elements --- bangdori/Top K Frequent Elements.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 bangdori/Top K Frequent Elements.js diff --git a/bangdori/Top K Frequent Elements.js b/bangdori/Top K Frequent Elements.js new file mode 100644 index 0000000..341b4e2 --- /dev/null +++ b/bangdori/Top K Frequent Elements.js @@ -0,0 +1,28 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function (nums, k) { + const map = new Map(); + + for (const num of nums) { + let count = 1; + + if (map.has(num)) { + const prevCount = map.get(num); + count += prevCount; + } + + map.set(num, count); + } + + const numsWithCount = [...map].sort((a, b) => b[1] - a[1]); + const answer = []; + + for (let i = 0; i < k; i++) { + answer.push(numsWithCount[i][0]); + } + + return answer; +};