Skip to content

Commit 1b27cf3

Browse files
committed
feat: Add solution for LeetCode problem 347
1 parent a0e4583 commit 1b27cf3

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
//
2+
// 347. Top K Frequent Elements
3+
// https://leetcode.com/problems/top-k-frequent-elements/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/01.
7+
//
8+
9+
final class Solution {
10+
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
11+
// Python의 Counter 모듈처럼 만드는 것과 동일
12+
var counter: [Int: Int] = [:]
13+
for number in nums {
14+
counter[number, default: 0] += 1
15+
}
16+
17+
return counter
18+
.sorted { lhs, rhs in
19+
lhs.value > rhs.value // 빈도 수를 기준으로 내림차순 정렬
20+
}
21+
.prefix(k) // 앞에서부터 k만큼 Subarray로 가져옴
22+
.map(\.key) // 제일 빈도가 많았던 것의 숫자를 가져옴 (Dictionary의 Key값)
23+
}
24+
}

0 commit comments

Comments
 (0)