3
3
public class TopKFrequentElements {
4
4
5
5
/**
6
- * 先统计每个元素次数,再用Priority排序
6
+ * 首选方法,时间复杂度O(n),省去了排序
7
+ * 结尾注意list的size大于k了,要截一部分
7
8
*/
8
- // 耗时46ms,最差复杂度O(nlgn),当k<<n时为O(n)
9
9
public List <Integer > topKFrequent (int [] nums , int k ) {
10
+ Map <Integer , Integer > map = new HashMap <Integer , Integer >();
11
+ int max = 0 ;
12
+ for (int n : nums ) {
13
+ int count = map .getOrDefault (n , 0 ) + 1 ;
14
+ map .put (n , count );
15
+ max = Math .max (max , count );
16
+ }
17
+ List <Integer >[] lists = new LinkedList [max + 1 ];
18
+ for (int key : map .keySet ()) {
19
+ int count = map .get (key );
20
+ if (lists [count ] == null ) {
21
+ lists [count ] = new LinkedList <Integer >();
22
+ }
23
+ lists [count ].add (key );
24
+ }
25
+ List <Integer > result = new LinkedList <Integer >();
26
+ for (int i = lists .length - 1 ; i >= 0 && result .size () < k ; i --) {
27
+ if (lists [i ] != null ) {
28
+ result .addAll (lists [i ]);
29
+ }
30
+ }
31
+ return result .subList (0 , k );
32
+ }
33
+
34
+ /**
35
+ * 先统计每个元素次数,再用Priority排序
36
+ */
37
+ // 耗时46ms,最差复杂度O(nlgk),当k<<n时为O(n)
38
+ public List <Integer > topKFrequent2 (int [] nums , int k ) {
10
39
HashMap <Integer , Integer > map = new HashMap <>();
11
40
for (int n : nums ) {
12
41
map .put (n , map .getOrDefault (n , 0 ) + 1 );
@@ -30,7 +59,7 @@ public int compare(Integer o1, Integer o2) {
30
59
return list ;
31
60
}
32
61
33
- public List <Integer > topKFrequent2 (int [] nums , int k ) {
62
+ public List <Integer > topKFrequent3 (int [] nums , int k ) {
34
63
Map <Integer , Integer > map = new HashMap <>();
35
64
for (int n : nums ){
36
65
map .put (n , map .getOrDefault (n ,0 )+1 );
@@ -52,31 +81,4 @@ public List<Integer> topKFrequent2(int[] nums, int k) {
52
81
}
53
82
return res ;
54
83
}
55
-
56
- // 耗时23ms,时间复杂度O(n),空间复杂度O(n)
57
- // 这里有个问题,result的size可能大于k了
58
- public List <Integer > topKFrequent3 (int [] nums , int k ) {
59
- Map <Integer , Integer > map = new HashMap <Integer , Integer >();
60
- int max = 0 ;
61
- for (int n : nums ) {
62
- int count = map .getOrDefault (n , 0 ) + 1 ;
63
- map .put (n , count );
64
- max = Math .max (max , count );
65
- }
66
- List <Integer >[] lists = new LinkedList [max + 1 ];
67
- for (int key : map .keySet ()) {
68
- int count = map .get (key );
69
- if (lists [count ] == null ) {
70
- lists [count ] = new LinkedList <Integer >();
71
- }
72
- lists [count ].add (key );
73
- }
74
- List <Integer > result = new LinkedList <Integer >();
75
- for (int i = lists .length - 1 ; i >= 0 && result .size () < k ; i --) {
76
- if (lists [i ] != null ) {
77
- result .addAll (lists [i ]);
78
- }
79
- }
80
- return result .subList (0 , k );
81
- }
82
84
}
0 commit comments