@@ -25,6 +25,7 @@ public class _347 {
25
25
public static class Solution1 {
26
26
/**
27
27
* Use buckets to hold numbers of the same frequency
28
+ * It's averaged at 30 ms on Leetcode.
28
29
*/
29
30
public List <Integer > topKFrequent (int [] nums , int k ) {
30
31
Map <Integer , Integer > map = new HashMap ();
@@ -55,7 +56,7 @@ public List<Integer> topKFrequent(int[] nums, int k) {
55
56
56
57
public static class Solution2 {
57
58
/**
58
- * Use hashtable and heap
59
+ * Use hashtable and heap, it's averaged at 100 ms on Leetocde.
59
60
*/
60
61
public List <Integer > topKFrequent (int [] nums , int k ) {
61
62
// construct the frequency map first, and then iterate through the map
@@ -66,15 +67,7 @@ public List<Integer> topKFrequent(int[] nums, int k) {
66
67
}
67
68
68
69
// build heap, this is O(logn)
69
- Queue <Entry <Integer , Integer >> heap = new PriorityQueue <>((o1 , o2 ) -> {
70
- if (o1 .getValue () > o2 .getValue ()) {
71
- return -1 ;
72
- } else if (o1 .getValue () < o2 .getValue ()) {
73
- return 1 ;
74
- } else {
75
- return 0 ;
76
- }
77
- });
70
+ Queue <Entry <Integer , Integer >> heap = new PriorityQueue <>((o1 , o2 ) -> o2 .getValue () - o1 .getValue ());
78
71
for (Entry <Integer , Integer > entry : map .entrySet ()) {
79
72
heap .offer (entry );
80
73
}
0 commit comments