File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ // MARK: 리뷰를 받고 시도해본 다른 풀이 (time: O(n), space O(n)
2+ class Solution {
3+ func topKFrequent( _ nums: [ Int ] , _ k: Int ) -> [ Int ] {
4+ // 빈도수 별로 Dictionary에 저장
5+ var dict = [ Int: Int] ( )
6+ for num in nums {
7+ dict [ num, default: 0 ] += 1
8+ }
9+ // Bucket sort 사용, 크기는 nums 만큼, 빈도수가 nums 공간보다 클수는 없으니까
10+ var bucket = Array ( repeating: [ Int] ( ) , count: nums. count + 1 )
11+ for (key, value) in dict {
12+ // 빈도수를 인덱스로 key == num 을 저장함
13+ // 배열로 한 이유는 빈도수가 같은게 있을 수 있으니까!
14+ bucket [ value] . append ( key)
15+ }
16+
17+ // 결과 출력
18+ var answer = [ Int] ( )
19+ // bucket의 뒤에서부터 탐색
20+ for index in stride ( from: nums. count, to: 0 , by: - 1 ) {
21+ // 없으면 무시
22+ guard !bucket[ index] . isEmpty else { continue }
23+ // 버켓의 현재 인덱스에 nil이 아니면 하나씩 결과에 추가해줌.
24+ for item in bucket [ index] {
25+ answer. append ( item)
26+ // k개 만큼 가져왔다면 바로 리턴
27+ if answer. count == k { return answer }
28+ }
29+ }
30+
31+ return answer
32+ }
33+ }
34+ // MARK: time: O(nlogn), space: O(n)
35+ // n+nlogn+n
136class Solution {
237 func topKFrequent( _ nums: [ Int ] , _ k: Int ) -> [ Int ] {
338 var dict = [ Int: Int] ( )
You can’t perform that action at this time.
0 commit comments