File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ 시간 복잡도 O(N)
3
+ 공간 복잡도 O(N)
4
+
5
+ Priority Queue 를 이용한 풀이
6
+ 시간 복잡도 O(Nlog(N))
7
+ 공간 복잡도 O(N)
8
+ from queue import PriorityQueue
9
+ from collections import Counter
10
+
11
+ class Solution:
12
+ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
13
+ counter = Counter(nums)
14
+ que = PriorityQueue()
15
+
16
+ for num, freq in counter.items():
17
+ que.put((-freq, num))
18
+
19
+ res = []
20
+
21
+ for _ in range(k):
22
+ res.append(que.get()[1])
23
+
24
+ return res
25
+ """
26
+ from collections import Counter
27
+
28
+ class Solution :
29
+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
30
+ freq_map = Counter (nums )
31
+
32
+ bucket = [[] for _ in range (len (nums ) + 1 )]
33
+
34
+ for num , freq in freq_map .items ():
35
+ bucket [freq ].append (num )
36
+
37
+ result = []
38
+
39
+ for i in range (len (bucket ) - 1 , - 1 , - 1 ):
40
+ if bucket [i ]:
41
+ for num in bucket [i ]:
42
+ result .append (num )
43
+ if len (result ) == k :
44
+ return result
45
+
You can’t perform that action at this time.
0 commit comments