Skip to content

Commit 5212548

Browse files
committed
Solved 237. Top K Frequent Elements problem
1 parent 365c1cc commit 5212548

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
Title: 237. Top K Frequent Elements
3+
Link: https://leetcode.com/problems/top-k-frequent-elements/
4+
5+
Question:
6+
- Given an integer array `nums` and an integer `k`, return the `k` most frequent elements.
7+
- You may return the answer in any order.
8+
9+
Constraints:
10+
- 1 <= nums.length <= 10^5
11+
- -10^4 <= nums[i] <= 10^4
12+
- k is in the range [1, the number of unique elements in the array].
13+
- The answer is guaranteed to be unique.
14+
15+
Time Complexity:
16+
- O(n log n)
17+
Space Complexity:
18+
- O(n)
19+
"""
20+
21+
class Solution:
22+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
23+
frequency = {}
24+
result = []
25+
for num in nums:
26+
if num in frequency:
27+
frequency[num] += 1
28+
else:
29+
frequency[num] = 1
30+
sorted_frequency = sorted(frequency.items(), key=lambda x: x[1], reverse=True)
31+
for i in range(k):
32+
result.append(sorted_frequency[i][0])
33+
return result

0 commit comments

Comments
 (0)