Skip to content

Commit fdbee2c

Browse files
committed
add solution top k frequent elements
1 parent 80a4899 commit fdbee2c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from typing import List
2+
3+
# Time Complexity O(n log n)
4+
# - traversing for loop takes O(n) to create hash dictionary,
5+
# - and when sorting by sorted function(TimSort) it takes O(nlogn)
6+
# Space Complexity O(n log n)
7+
# - creating hash dictionary takes O(n)
8+
# - and when sorting takes O(n), hash[x] occupy O(1)
9+
10+
class Solution:
11+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
12+
hash = dict()
13+
14+
# for loop nums to set count for each element in hash(dictionary)
15+
for num in nums:
16+
if num in hash:
17+
hash[num] += 1
18+
else:
19+
hash[num] = 1
20+
21+
# sort (TimSort), using lambda function to set a sorting key which is a count
22+
return sorted(hash, key=lambda x: hash[x], reverse=True)[:k]
23+
24+
if __name__ == "__main__":
25+
solution = Solution()
26+
27+
# test case
28+
nums_list = [
29+
[1,1,1,2,2,3], # [1, 2]
30+
[1] # [1]
31+
]
32+
k_list = [2, 1]
33+
34+
for i in range(2):
35+
nums = nums_list[i]
36+
k = k_list[i]
37+
result = solution.topKFrequent(nums, k)
38+
print(f"start{i}")
39+
print(f"input : {nums}, {k}")
40+
print(f"result : {result}")
41+

0 commit comments

Comments
 (0)