File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ class Solution {
4+ // return: top k most freq elements
5+ public int [] topKFrequent (int [] nums , int k ) {
6+ HashMap <Integer , Integer > freq = new HashMap <>();
7+ // O (N)
8+ for (int num : nums ) {
9+ freq .put (num , freq .getOrDefault (num , 0 ) + 1 ); // O(1)
10+ }
11+
12+ // O (N log k)
13+ PriorityQueue <int []> heap = new PriorityQueue <>(Comparator .comparingInt (a -> a [1 ]));
14+ for (int num : freq .keySet ()) {
15+ int f = freq .get (num ); // O(1)
16+ heap .add (new int []{num , f }); // O(log k)
17+
18+ if (heap .size () > k ) heap .poll (); // O(log k)
19+ }
20+
21+ // O (N log k)
22+ int [] result = new int [k ];
23+ for (int i = 0 ; i < k ; i ++) {
24+ result [i ] = heap .poll ()[0 ]; // O(log k)
25+ }
26+
27+ return result ;
28+ }
29+ }
You can’t perform that action at this time.
0 commit comments