File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Solution:
3
+ 1. make a dictionary of (index, Frequency)
4
+ 2. sort the items of dictionary by Frequency
5
+ 3. return list of Top k Frequent Elements
6
+
7
+ Time Complexity:
8
+ 1. iterate nums for counting -> O(n)
9
+ 2. sort -> O(n log n)
10
+ 3. iterate list for making return value -> O(n)
11
+
12
+ So Time complexity of this solution is O(n log n)
13
+
14
+ Space Complexity:
15
+ 1. dictionary for counting frequency of nums -> O(n)
16
+ 2. sorted List -> O(n)
17
+
18
+ Space complexity of this solution is O(n)
19
+ """
20
+
21
+
22
+ class Solution :
23
+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
24
+ counts = defaultdict (int )
25
+ for num in nums :
26
+ counts [num ] += 1
27
+
28
+ result = sorted (counts .items (), key = lambda x : x [1 ], reverse = True )
29
+ return list (map (lambda x : x [0 ], result [:k ]))
You can’t perform that action at this time.
0 commit comments