-
Notifications
You must be signed in to change notification settings - Fork 0
/
TopKBestSolu.java
86 lines (62 loc) · 1.92 KB
/
TopKBestSolu.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.*;
class TopKFreqEle {
public static void main(String[] args) {
int nums[]={10000,1,90,1};
int k=2;
topKFrequent(nums,2);
}
public static int[] topKFrequent(int[] nums, int k) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i : nums) {
if (min > i) {
min = i;
}
if (i > max) {
max = i;
}
}
int[] frequency = new int[max - min + 1];
for (int num : nums) {
frequency[num - min]++;
}
List<Integer>[] buckets = new List[nums.length + 1];
List<Integer> bucketList = new ArrayList<>(nums.length);
for (int i = 0; i < 10; i++) {
bucketList.add(0);
}
int maxFrequency = 0;
// for (int i = 0; i < frequency.length; i++) {
//
// if (frequency[i] > 0) {
//
// // if (bucketList.get(frequency[i])== null) {
// bucketList.set(frequency[i], i+min);
// //}
//
// maxFrequency = Math.max(frequency[i], maxFrequency);
// }
// }
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] > 0) {
if (buckets[frequency[i]] == null) {
buckets[frequency[i]] = new ArrayList<>();
}
buckets[frequency[i]].add(i + min);
maxFrequency = Math.max(frequency[i], maxFrequency);
}
}
int[] result = new int[k];
for (int i = maxFrequency, index = 0; i > 0 && index < k; i--) {
if (buckets[i] != null) {
for (int num : buckets[i]) {
if (index == k) {
break;
}
result[index++] = num;
}
}
}
return result;
}
}