File tree 2 files changed +34
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +34
-0
lines changed Original file line number Diff line number Diff line change 7
7
import java .util .Map .Entry ;
8
8
import java .util .PriorityQueue ;
9
9
import java .util .Queue ;
10
+ import java .util .TreeMap ;
10
11
11
12
public class _347 {
12
13
@@ -74,4 +75,34 @@ public int[] topKFrequent(int[] nums, int k) {
74
75
return arr ;
75
76
}
76
77
}
78
+
79
+ public static class Solution3 {
80
+ /**
81
+ * Use hashtable and heap, it's averaged at 10 ms on Leetocde.
82
+ */
83
+ public int [] topKFrequent (int [] nums , int k ) {
84
+ Map <Integer , Integer > map = new HashMap <>();
85
+ for (int i : nums ) {
86
+ map .put (i , map .getOrDefault (i , 0 ) + 1 );
87
+ }
88
+ TreeMap <Integer , List <Integer >> treeMap = new TreeMap <>((a , b ) -> b - a );
89
+ for (int key : map .keySet ()) {
90
+ List <Integer > list = treeMap .getOrDefault (map .get (key ), new ArrayList <>());
91
+ list .add (key );
92
+ treeMap .put (map .get (key ), list );
93
+ }
94
+ List <Integer > list = new ArrayList <>();
95
+ while (!treeMap .isEmpty ()) {
96
+ list .addAll (treeMap .pollFirstEntry ().getValue ());
97
+ if (list .size () == k ) {
98
+ break ;
99
+ }
100
+ }
101
+ int [] ans = new int [list .size ()];
102
+ for (int i = 0 ; i < list .size (); i ++) {
103
+ ans [i ] = list .get (i );
104
+ }
105
+ return ans ;
106
+ }
107
+ }
77
108
}
Original file line number Diff line number Diff line change 9
9
public class _347Test {
10
10
private static _347 .Solution1 solution1 ;
11
11
private static _347 .Solution2 solution2 ;
12
+ private static _347 .Solution3 solution3 ;
12
13
private static int [] nums ;
13
14
private static int [] expected ;
14
15
15
16
@ BeforeClass
16
17
public static void setup () {
17
18
solution1 = new _347 .Solution1 ();
18
19
solution2 = new _347 .Solution2 ();
20
+ solution3 = new _347 .Solution3 ();
19
21
}
20
22
21
23
@ Test
@@ -35,6 +37,7 @@ public void test2() {
35
37
nums = new int []{3 , 0 , 1 , 0 };
36
38
expected = new int []{0 , 3 };
37
39
assertArrayEquals (expected , solution2 .topKFrequent (nums , 2 ));
40
+ assertArrayEquals (expected , solution3 .topKFrequent (nums , 2 ));
38
41
}
39
42
40
43
@ Test
You can’t perform that action at this time.
0 commit comments