Skip to content

Commit 38b14d0

Browse files
authored
Create topKFrequent.py
1 parent 4177cc3 commit 38b14d0

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

topKFrequent.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution:
2+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3+
count = {}
4+
freq = [[] for i in range(len(nums) + 1)]
5+
for n in nums:
6+
count[n] = 1 + count.get(n, 0)
7+
for n, c in count.items():
8+
freq[c].append(n)
9+
res = []
10+
for i in range(len(freq)-1, 0 , -1):
11+
for n in freq[i]:
12+
res.append(n)
13+
if len(res) == k:
14+
return res[-1::-1]
15+

0 commit comments

Comments
 (0)