Skip to content

Commit 116161f

Browse files
committed
347. Top K Frequent Elements
1 parent d5c86da commit 116161f

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
var topKFrequent = function(nums, k) {
7+
// 1. nums 배열을 순회하여 각 숫자의 빈도를 계산하고 obj 객체에 저장
8+
const obj = nums.reduce((arr, idx) => {
9+
arr[idx] = (arr[idx] || 0) + 1;
10+
return arr;
11+
}, {});
12+
13+
// 2. obj 객체의 키-값 쌍을 배열로 변환하고, 값을 기준으로 내림차순 정렬, k개 추출
14+
const frequentArr = Object.entries(obj)
15+
.sort(([, valueA], [, valueB]) => valueB - valueA)
16+
.slice(0, k)
17+
.map(([key]) => +key);
18+
19+
return frequentArr;
20+
};

0 commit comments

Comments
 (0)