File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
3+ # Frequency
4+ freq = defaultdict (int )
5+ for n in nums :
6+ freq [n ] += 1
7+
8+ freq_list = []
9+ for key , val in freq .items ():
10+ freq_list .append ((- 1 * val , key ))
11+
12+ heapq .heapify (freq_list )
13+
14+ res = []
15+ for _ in range (k ):
16+ res .append (heapq .heappop (freq_list )[1 ])
17+
18+ return res
19+
20+ # T: nlogn
21+ # S: n
22+
23+ def topKFrequent2 (self , nums : List [int ], k : int ) -> List [int ]:
24+ res = []
25+ # Frequency
26+ count = defaultdict (int )
27+ for n in nums :
28+ count [n ] += 1
29+
30+ # Convert to frequency
31+ frequency = [[] for _ in range (len (nums ) + 1 )]
32+ for key , freq in count .items ():
33+ frequency [freq ].append (key )
34+
35+ # top K
36+ for freq in range (len (nums ), 0 , - 1 ):
37+ for n in frequency [freq ]:
38+ res .append (n )
39+
40+ if len (res ) == k :
41+ return res
42+ # T: n
43+ # S: n
44+
You can’t perform that action at this time.
0 commit comments