We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent d5c86da commit 116161fCopy full SHA for 116161f
top-k-frequent-elements/y00eunji.js
@@ -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