Skip to content

Commit 659e802

Browse files
committed
Bucket Solution for Top K Frequent Elements #237
1 parent b613632 commit 659e802

1 file changed

Lines changed: 26 additions & 21 deletions

File tree

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,47 @@
11
import java.util.HashMap;
2-
import java.util.Map;
3-
import java.util.PriorityQueue;
4-
import java.util.Comparator;
2+
import java.util.ArrayList;
53

6-
public class dohyeon2 {
4+
class Solution {
75
public int[] topKFrequent(int[] nums, int k) {
8-
// approach :
9-
// 1. create map to match num to frequency
10-
// 2. create max frequency Priority Queue for sort
11-
// 3. pop the max value from the queue until k
12-
// time complexity O(n log n) : priority queue comparison
6+
// time complexity O(n)
137
// space complexity O(n)
148

15-
// ChatGPT says that there is O(n) solution for this, how?
169
HashMap<Integer, Integer> frequentMap = new HashMap<>();
1710

1811
for (int i = 0; i < nums.length; i++) {
1912
int num = nums[i];
2013
frequentMap.merge(num, 1, Integer::sum);
2114
}
2215

23-
PriorityQueue<Map.Entry<Integer, Integer>> PQ = new PriorityQueue<>(k,
24-
Comparator.comparing(Map.Entry<Integer, Integer>::getValue).reversed());
16+
ArrayList<Integer>[] buckets = new ArrayList[nums.length + 1];
2517

26-
for(Map.Entry<Integer,Integer> e : frequentMap.entrySet()){
27-
PQ.add(e);
18+
for (int i = 0; i <= nums.length; i++) {
19+
buckets[i] = new ArrayList<>();
2820
}
2921

30-
int[] result = new int[k];
22+
frequentMap.forEach((Integer a, Integer b) -> {
23+
// Assign the largest values from the front of the array
24+
buckets[nums.length - b].add(a);
25+
});
3126

32-
int idx = 0;
27+
int[] result = new int[k];
3328

34-
while (idx < k && PQ.size() > 0) {
35-
Map.Entry<Integer, Integer> v = PQ.poll();
36-
result[idx] = (int) v.getKey();
37-
idx++;
29+
int pointer = 0;
30+
31+
for (int i = 0; i < buckets.length; i++) {
32+
ArrayList<Integer> list = buckets[i];
33+
if (list.size() == 0) {
34+
continue;
35+
}
36+
for (Integer num : list) {
37+
result[pointer] = (int) num;
38+
// Return the result when the pointer reaches k
39+
if (pointer == (k - 1))
40+
return result;
41+
pointer++;
42+
}
3843
}
3944

4045
return result;
4146
}
42-
}
47+
}

0 commit comments

Comments
 (0)