1
+ # 347. Top K Frequent Elements
2
+ # 🟠 Medium
3
+ #
1
4
# https://leetcode.com/problems/top-k-frequent-elements/
5
+ #
6
+ # Tags: Array - Hash Table - Divide and Conquer - Sorting
7
+ # - Heap (Priority Queue) - Bucket Sort - Counting - Quickselect
2
8
3
9
import timeit
4
10
from collections import Counter
5
11
from typing import List
6
12
7
13
8
- # Iterate over the elements in nums creating a dictionary with num => num_times_seen
9
- # Return the k most seen elements in the dictionary. For simplicity this solution uses Counter .
14
+ # Use the built- in Python Counter to count the elements and its
15
+ # `most_common(n)` method to get the k most frequent .
10
16
#
11
17
# Time complexity: O(n*log(n)) - Sorting the dictionary by value.
12
18
# Space complexity: O(n) - The size of the dictionary.
13
19
#
14
- # Runtime: 163 ms, faster than 48.84% of Python3 online submissions for Top K Frequent Elements.
15
- # Memory Usage: 18.6 MB, less than 91.62% of Python3 online submissions for Top K Frequent Elements.
20
+ # Runtime 95 ms Beats 95.19%
21
+ # Memory Usage 18.4 Beats 99.66%
16
22
class Solution :
17
23
def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
18
24
return [x [0 ] for x in Counter (nums ).most_common (k )]
@@ -21,25 +27,27 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
21
27
def test ():
22
28
executors = [Solution ]
23
29
tests = [
30
+ [[1 ], 1 , [1 ]],
24
31
[[3 , 0 , 1 , 0 ], 1 , [0 ]],
32
+ [[1 , 1 , 1 , 2 , 2 , 3 ], 2 , [1 , 2 ]],
25
33
[[1 , 1 , 1 , 2 , 2 , 2 , 2 , 3 ], 3 , [2 , 1 , 3 ]],
26
34
[[1 , 4 , 1 , 1 , 2 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 4 , 3 ], 3 , [3 , 2 , 1 ]],
27
- [[1 , 1 , 1 , 2 , 2 , 3 ], 2 , [1 , 2 ]],
28
- [[1 ], 1 , [1 ]],
29
35
]
30
36
for executor in executors :
31
37
start = timeit .default_timer ()
32
- for _ in range (int ( float ( "1" )) ):
38
+ for _ in range (1 ):
33
39
for col , t in enumerate (tests ):
34
40
sol = executor ()
35
41
result = sol .topKFrequent (t [0 ], t [1 ])
36
42
exp = t [2 ]
37
- assert (
38
- result .sort () == exp .sort ()
39
- ), f"\033 [93m» { result } <> { exp } \033 [91m for test { col } using \033 [1m{ executor .__name__ } "
43
+ assert result == exp , (
44
+ f"\033 [93m» { result } <> { exp } \033 [91m for"
45
+ + f" test { col } using \033 [1m{ executor .__name__ } "
46
+ )
40
47
stop = timeit .default_timer ()
41
48
used = str (round (stop - start , 5 ))
42
- res = "{0:20}{1:10}{2:10}" .format (executor .__name__ , used , "seconds" )
49
+ cols = "{0:20}{1:10}{2:10}"
50
+ res = cols .format (executor .__name__ , used , "seconds" )
43
51
print (f"\033 [92m» { res } \033 [0m" )
44
52
45
53
0 commit comments