Skip to content

Commit c56be68

Browse files
committed
top-k-frequent-elements: use Counter
1 parent c4b46ab commit c56be68

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

โ€Žtop-k-frequent-elements/haklee.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,20 @@
77
Average Case O(1) ์ ์šฉ ๊ฐ€์ •
88
99
2
10-
dict์˜ (๊ฐ’, ํ‚ค) ํŠœํ”Œ์„ sortingํ•˜๋Š” ๋ฐ์— TC: O(n log n), SC: O(n)
10+
ref: https://docs.python.org/3/library/collections.html#collections.Counter
11+
A Counter is a dict subclass for counting hashable objects.
12+
13+
Counter, ์ฆ‰, dict์˜ (๊ฐ’, ํ‚ค) ํŠœํ”Œ์„ sortingํ•˜๋Š” ๋ฐ์— TC: O(n log n), SC: O(n)
1114
* ์ด๋•Œ ๊ฐ’์ด ํด์ˆ˜๋ก ์•ž์— ์˜ค๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด ๊ฐ’์„ ์Œ์ˆ˜๋กœ ๋ฐ”๊ฟ”์คฌ๋‹ค.
1215
1316
3
1417
sorted๋œ ๋ฆฌ์ŠคํŠธ์—์„œ ํŠœํ”Œ์˜ ๋‘ ๋ฒˆ์งธ ์•„์ดํ…œ๋งŒ ๋ฝ‘์€ ๋‹ค์Œ์—
1518
๋ฆฌ์ŠคํŠธ์˜ ์•ž k๊ฐœ์˜ ์•„์ดํ…œ ๋ฆฌํ„ด.
1619
"""
1720

21+
from collections import Counter
22+
1823

1924
class Solution:
2025
def topKFrequent(self, nums: List[int], n: int) -> List[int]:
21-
d = {}
22-
[d.update({i: d.get(i, 0) + 1}) for i in nums]
23-
return [i for _, i in sorted([(-v, k) for k, v in d.items()])][:n]
26+
return [i for _, i in sorted([(-v, k) for k, v in Counter(nums).items()])][:n]

0 commit comments

Comments
ย (0)