Skip to content

Commit a309b1e

Browse files
author
MJ Kang
committed
top k elements
1 parent 3c1ea6a commit a309b1e

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from typing import List
2+
3+
class Solution:
4+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
5+
countDict = {}
6+
for num in nums:
7+
if num in countDict:
8+
countDict[num] += 1
9+
else:
10+
countDict[num] = 1
11+
sortedDictList = sorted(countDict.items(), key=lambda item: item[1], reverse = True)
12+
freqElements = []
13+
for i in range(k):
14+
freqElements.append(sortedDictList[i][0])
15+
return freqElements

0 commit comments

Comments
 (0)