File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
You canโt perform that action at this time.
0 commit comments