File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """
2+ # Intuition
3+ N is can be up to 100000, so time complexity should be O(N log N) at least.
4+ Calculate the frequency of its elements using dictionary, sort it, and list top K ones.
5+
6+ # Approach
7+ 1. for n in nums:
8+ 1-1. if n in map: map[n] += 1
9+ 2. sort it by its value
10+ 3. slice and return top K
11+
12+ # Complexity
13+ Let:
14+ - N = len(nums)
15+ - M = number of unique elements in nums
16+
17+ Time complexity:
18+ - O(N) + O(M log M) + O(K)
19+ - O(N log N) when all elements are unique.
20+
21+ Space complexity:
22+ - O(M) + O(M) + O(K)
23+ - Overall: O(N) in the worst case.
24+ """
25+
26+ from collections import defaultdict
27+
28+
29+ class Solution :
30+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
31+ dic = defaultdict (int )
32+ for n in nums :
33+ dic [n ] += 1
34+ value_sorted = sorted (dic .items (), key = lambda x : - x [1 ])
35+ return [i [0 ] for i in value_sorted [:k ]]
You can’t perform that action at this time.
0 commit comments