Skip to content

Commit 999f6e3

Browse files
committed
top-k-frequrent-elements solved
1 parent abe5952 commit 999f6e3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

top-k-frequent-elements/kut7728.swift

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

0 commit comments

Comments
 (0)