Skip to content

Commit 192ef04

Browse files
committed
- Solution for "Top K Frequent Elements #237"
1 parent 1343e82 commit 192ef04

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

top-k-frequent-elements/ayosecu.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from typing import List
2+
from collections import Counter
3+
4+
class Solution:
5+
"""
6+
- Time Complexity: O(nlogk), n = len(nums)
7+
- Counter(nums) => O(n)
8+
- Counter.most_common(k) => O(nlogk)
9+
- O(n) + O(nlogk) => O(nlogk)
10+
- Space Complexity: O(N)
11+
- N = len(counter_nums) = The number of unique numbers
12+
- Worst case => No duplicated numbers => N = n
13+
"""
14+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
15+
c = Counter(nums)
16+
return [key for (key, val) in c.most_common(k)]
17+
18+
tc = [
19+
([1,1,1,2,2,3], 2, [1, 2]),
20+
([1], 1, [1])
21+
]
22+
23+
for i, (nums, k, e) in enumerate(tc, 1):
24+
sol = Solution()
25+
result = sol.topKFrequent(nums, k)
26+
result.sort()
27+
print(f"TC {i} is Passed!" if result == e else f"TC {i} is Failed! - Expected: {e}, Result: {result}")

0 commit comments

Comments
 (0)