Skip to content

Commit ffaa6d8

Browse files
committed
Add comments to top-k-frequent-element
1 parent b2b7792 commit ffaa6d8

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed
Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
class Solution {
22
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
33
var dictionary: [Int: Int] = [:]
4-
for num in nums {
4+
for num in nums { // for loop๋ฅผ ๋Œ๋ฉด์„œ O(n)์˜ ์‹œ๊ฐ„๋ณต์žก๋„
55
dictionary[num, default: 0] += 1
6+
// Swift์—์„œ dictionary ๊ฒ€์ƒ‰์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(1)
67
}
78

8-
return dictionary.sorted(by: { $0.value > $1.value }).prefix(k).map(\.key)
9+
return dictionary
10+
.sorted(by: { $0.value > $1.value })
11+
// dictionary sorted()์˜ ์‹œ๊ฐ„๋ณต์žก๋„ O(n log n)
12+
.prefix(k)
13+
// k์˜ ๊ฐœ์ˆ˜๋งŒํผ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค. ๊ณ ๋กœ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(n)
14+
.map(\.key)
15+
// prefix์—์„œ k๋งŒํผ ํƒ์ƒ‰ํ•˜์˜€์Šต๋‹ˆ๋‹ค.
16+
// .map์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(n)์ž…๋‹ˆ๋‹ค.
917
}
1018
}
1119

0 commit comments

Comments
ย (0)