Skip to content

Commit fed0fd4

Browse files
committed
solve(w01): 347. Top K Frequent Elements
1 parent 3bce933 commit fed0fd4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# https://leetcode.com/problems/top-k-frequent-elements/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
7+
"""
8+
[Complexity]
9+
- TC: O(n + klogn)
10+
- SC: O(n)
11+
12+
[Approach]
13+
1. nums๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ์›์†Œ๋ณ„ ๋“ฑ์žฅ ํšŸ์ˆ˜๋ฅผ ์นด์šดํŠธํ•œ๋‹ค.
14+
2. min heap์— (-๋“ฑ์žฅ ํšŸ์ˆ˜, ์›์†Œ) ํ˜•ํƒœ์˜ tuple์„ ์ €์žฅํ•œ๋‹ค.
15+
3. k๋ฒˆ pop ํ•˜๋ฉด, k most frequent elements๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.
16+
"""
17+
import heapq
18+
from collections import Counter
19+
20+
# 0. early stop
21+
if len(nums) == k:
22+
return nums
23+
24+
# 1. ๋“ฑ์žฅ ํšŸ์ˆ˜ ์นด์šดํŠธ
25+
cnt = Counter(nums) # -- O(n)
26+
27+
# 2. min heap์— ์ €์žฅ
28+
q = [(-c, num) for num, c in cnt.items()] # -- O(n)
29+
heapq.heapify(q) # -- O(n)
30+
31+
# 3. k๋ฒˆ pop
32+
res = []
33+
for _ in range(k): # -- O(k)
34+
_, num = heapq.heappop(q) # -- O(logn)
35+
res.append(num)
36+
37+
return res

0 commit comments

Comments
ย (0)