We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 30eb1b1 commit 81fdc17Copy full SHA for 81fdc17
top-k-frequent-elements/sunjae95.js
@@ -16,16 +16,14 @@
16
17
var topKFrequent = function (nums, k) {
18
const answer = [];
19
- const array = [];
20
const hashTable = new Map();
21
22
nums.forEach((num) => hashTable.set(num, (hashTable.get(num) ?? 0) + 1));
23
24
- hashTable.forEach((count, number) => array.push({ number, count }));
+ hashTable.forEach((count, number) => answer.push({ number, count }));
25
26
- array.sort((a, b) => b.count - a.count);
27
-
28
- for (let i = 0; i < k; i++) answer.push(array[i].number);
29
30
- return answer;
+ return answer
+ .sort((a, b) => b.count - a.count)
+ .slice(0, k)
+ .map(({ number }) => number);
31
};
0 commit comments