File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments