File tree 1 file changed +51
-0
lines changed 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ /*
3
+ 1차 시도
4
+ 복잡도 - O(n log n)
5
+ func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
6
+ var list: [Int:Int] = [:]
7
+ var result: [Int] = []
8
+ if nums.count == 1 { return nums }
9
+
10
+ for i in nums {
11
+ list[i, default: 0] += 1
12
+ }
13
+
14
+ var sortedList = list.sorted { $0.value > $1.value }
15
+ print(sortedList)
16
+
17
+ for i in 0..<k {
18
+ let target = sortedList[i].key
19
+ result.append(target)
20
+ // sortedList[target] = 0
21
+ }
22
+ return result
23
+ } */
24
+
25
+ // 2차 시도 : 복잡도 - O(n)
26
+ class Solution {
27
+ func topKFrequent( _ nums: [ Int ] , _ k: Int ) -> [ Int ] {
28
+ var freqMap = [ Int: Int] ( )
29
+
30
+ for num in nums {
31
+ freqMap [ num, default: 0 ] += 1
32
+ }
33
+
34
+ // 버켓에 빈도수를 인덱스로 값을 저장
35
+ var buckets = Array ( repeating: [ Int] ( ) , count: nums. count + 1 )
36
+ for (num, freq) in freqMap {
37
+ buckets [ freq] . append ( num)
38
+ }
39
+
40
+ var result = [ Int] ( )
41
+ for i in ( 0 ..< buckets. count) . reversed ( ) {
42
+ result += buckets [ i]
43
+ if result. count == k {
44
+ break
45
+ }
46
+ }
47
+
48
+ return result
49
+ }
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments