Skip to content

Commit 5c3f9aa

Browse files
committed
LC 347. Top K Frequent Elements (Python Reforma)t
1 parent 4aeef66 commit 5c3f9aa

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

leetcode/top-k-frequent-elements.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
1+
# 347. Top K Frequent Elements
2+
# 🟠 Medium
3+
#
14
# 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
28

39
import timeit
410
from collections import Counter
511
from typing import List
612

713

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.
1016
#
1117
# Time complexity: O(n*log(n)) - Sorting the dictionary by value.
1218
# Space complexity: O(n) - The size of the dictionary.
1319
#
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%
1622
class Solution:
1723
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
1824
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]:
2127
def test():
2228
executors = [Solution]
2329
tests = [
30+
[[1], 1, [1]],
2431
[[3, 0, 1, 0], 1, [0]],
32+
[[1, 1, 1, 2, 2, 3], 2, [1, 2]],
2533
[[1, 1, 1, 2, 2, 2, 2, 3], 3, [2, 1, 3]],
2634
[[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]],
2935
]
3036
for executor in executors:
3137
start = timeit.default_timer()
32-
for _ in range(int(float("1"))):
38+
for _ in range(1):
3339
for col, t in enumerate(tests):
3440
sol = executor()
3541
result = sol.topKFrequent(t[0], t[1])
3642
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+
)
4047
stop = timeit.default_timer()
4148
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")
4351
print(f"\033[92m» {res}\033[0m")
4452

4553

0 commit comments

Comments
 (0)