Skip to content

Commit ae4fa90

Browse files
347. Top K Frequent Elements
Difficulty: Medium 21 / 21 test cases passed. Runtime: 112 ms Memory Usage: 18.5 MB
1 parent db6026e commit ae4fa90

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Medium/347.TopKFrequentElements.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
Given a non-empty array of integers, return the k most frequent elements.
3+
4+
Example:
5+
Input: nums = [1,1,1,2,2,3], k = 2
6+
Output: [1,2]
7+
8+
Note:
9+
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
10+
- Your algorithm's time complexity must be better than O(n log n), where
11+
n is the array's size.
12+
- It's guaranteed that the answer is unique, in other words the set of
13+
the top k frequent elements is unique.
14+
- You can return the answer in any order.
15+
"""
16+
#Difficulty: Medium
17+
#21 / 21 test cases passed.
18+
#Runtime: 112 ms
19+
#Memory Usage: 18.5 MB
20+
21+
#Runtime: 112 ms, faster than 51.73% of Python3 online submissions for Top K Frequent Elements.
22+
#Memory Usage: 18.5 MB, less than 8.25% of Python3 online submissions for Top K Frequent Elements.
23+
24+
class Solution:
25+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
26+
d = {}
27+
for num in nums:
28+
if num in d.keys():
29+
d[num] += 1
30+
else:
31+
d[num] = 1
32+
return [key[0] for key in sorted(d.items(), key=lambda item: item[1])][-k:]

0 commit comments

Comments
 (0)