forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsamcho0608.java
More file actions
70 lines (59 loc) · 1.98 KB
/
samcho0608.java
File metadata and controls
70 lines (59 loc) · 1.98 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
import java.util.*;
// link: https://leetcode.com/problems/top-k-frequent-elements/description/
// difficulty: Medium
// Time complexity: O(Nlogk)
// Space complexity: O(N)
class Solution1 {
// return: top k most freq elements
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> freq = new HashMap<>();
// O (N)
for(int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1); // O(1)
}
// O (N log k)
PriorityQueue<int[]> heap = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
for(int num : freq.keySet()) {
int f = freq.get(num); // O(1)
heap.add(new int[]{num, f}); // O(log k)
if(heap.size() > k) heap.poll(); // O(log k)
}
// O (N log k)
int[] result = new int[k];
for(int i = 0; i < k; i++) {
result[i] = heap.poll()[0]; // O(log k)
}
return result;
}
}
// Time complexity: O(N)
// Space complexity: O(N)
class Solution2 {
public int[] topKFrequent(int[] nums, int k) {
// count frequencies
Map<Integer, Integer> freq = new HashMap<>();
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
// bucket: index = frequency, value = list of numbers
List<List<Integer>> buckets = new ArrayList<>(nums.length + 1);
for (int i = 0; i <= nums.length; i++) {
buckets.add(new ArrayList<>());
}
for (var entry : freq.entrySet()) {
int num = entry.getKey();
int count = entry.getValue();
buckets.get(count).add(num);
}
// gather top k frequent elements
int[] result = new int[k];
int idx = 0;
for (int i = nums.length; i >= 0 && idx < k; i--) {
for (int num : buckets.get(i)) {
result[idx++] = num;
if (idx == k) break;
}
}
return result;
}
}