File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+
3
+
4
+ class Solution {
5
+ /* 시간 복잡도: O(N + M * log k)
6
+ * - for 루프: O(N), frequency 구하기
7
+ * - for 루프: O(M * log k), Map 순회
8
+ - Map 요소: M개
9
+ * - PriorityQueue 연산 (offer, poll): 평균 O(logk)
10
+ *
11
+ * 공간 복잡도: O(N + k), HashMap에 n개 + PriorityQueue에 k개
12
+ */
13
+ public int [] topKFrequent (int [] nums , int k ) {
14
+ Map <Integer , Integer > frequencyMap = new HashMap <>();
15
+ // [num, frequency]
16
+ PriorityQueue <int []> minHeap = new PriorityQueue <>((o1 , o2 ) -> {
17
+ return o1 [1 ] - o2 [1 ];
18
+ });
19
+ for (int num : nums ) {
20
+ frequencyMap .put (num , frequencyMap .getOrDefault (num , 0 ) + 1 );
21
+ }
22
+ for (var entry : frequencyMap .entrySet ()) {
23
+ minHeap .add (new int []{entry .getKey (), entry .getValue ()});
24
+ if (minHeap .size () > k ) {
25
+ minHeap .poll ();
26
+ }
27
+ }
28
+
29
+ int [] answer = new int [k ];
30
+ for (int i = 0 ; i < k ; i ++) {
31
+ answer [i ] = minHeap .poll ()[0 ];
32
+ }
33
+ return answer ;
34
+ }
35
+ }
36
+
You can’t perform that action at this time.
0 commit comments