-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path29_Top_K_freq.java
More file actions
127 lines (90 loc) · 2.96 KB
/
29_Top_K_freq.java
File metadata and controls
127 lines (90 loc) · 2.96 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
// Example 1:
// Input: nums = [1,1,1,2,2,3], k = 2
// Output: [1,2]
// Example 2:
// Input: nums = [1], k = 1
// Output: [1]
// Example 3:
// Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2
// Output: [1,2]
// GFG but not optimal solution
class Solution {
static class Compare implements Comparator<int[]> {
public int compare(int[] p1, int[] p2) {
if (p1[1] == p2[1])
return Integer.compare(p2[0], p1[0]);
return Integer.compare(p2[1], p1[1]);
}
}
public int[] topKFrequent(int[] nums, int k) {
int n = nums.length;
Map<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < n; i++)
mp.put(nums[i], mp.getOrDefault(nums[i], 0) + 1);
ArrayList<int[]> freq = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : mp.entrySet())
freq.add(new int[]{entry.getKey(), entry.getValue()});
freq.sort(new Compare());
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < k; i++) {
res.add(freq.get(i)[0]);
}
int[] ans = new int[k];
for (int i = 0; i < k; i++) ans[i] = res.get(i);
return ans;
}
}
// Leetcode optimal solution
public class Solution {
static {
int[] nums = {1, 1, 2, 2, 3};
for (int i = 0; i < 200; i++) {
topKFrequent(nums, 2);
}
}
public static int[] topKFrequent(int[] nums, int k) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int num : nums) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
int[] freq = new int[max - min + 1];
int max_freq = 0;
for (int num : nums) {
int dif = num - min;
int f = ++freq[dif];
if (f > max_freq) {
max_freq = f;
}
}
ArrayList<Integer>[] freqAr = new ArrayList[max_freq];
for (int i = 0; i < freq.length; i++) {
int n = freq[i] -1;
if (n == -1) {
continue;
}
if (freqAr[n] == null) {
freqAr[n] = new ArrayList<Integer>();
}
freqAr[n].add(i + min);
}
int[] res = new int[k];
int t = 0;
for (int i = max_freq - 1; i >= 0; i--) {
if (freqAr[i] == null) continue;
for (int j = 0; j < freqAr[i].size(); j++) {
res[t++] = freqAr[i].get(j);
if (t == k) {
return res;
}
}
}
return res;
}
}