Skip to content

Commit ff227d7

Browse files
committed
add: topKFrequentElements solution
1 parent f3ef852 commit ff227d7

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const topKFrequent = function (nums, k) {
2+
const tempArr = Array.from({ length: nums.length }, () => []);
3+
const obj = {};
4+
5+
for (let num of nums) {
6+
obj[num] = (obj[num] || 0) + 1;
7+
}
8+
9+
for (let key in obj) {
10+
const val = obj[key] - 1;
11+
tempArr[val].push(+key);
12+
}
13+
14+
const answer = tempArr.flat();
15+
return answer.slice(-k);
16+
};

0 commit comments

Comments
 (0)