Maximum Frequency Stack LeetCode solution in Java

1
class Node {
2
int data, freq, time;
3

4
Node(int data, int freq, int time) {
5
this.data = data;
6
this.freq = freq;
7
this.time = time;
8
}
9
}
10

11
class CompareNode implements Comparator<Node> {
12
@Override
13
public int compare(Node a, Node b) {
14
if (a.freq - b.freq == 0) {
15
return b.time - a.time;
16
}
17
return b.freq - a.freq;
18
}
19
}
20

21
class FreqStack {
22
PriorityQueue<Node> pq;
23
Map<Integer, Node> map;
24
int c = 0;
25

26
public FreqStack() {
27
pq = new PriorityQueue<>(new CompareNode());
28
map = new HashMap<>();
29
}
30

31
public void push(int val) {
32
c++;
33
int freq = 1;
34
if (map.containsKey(val)) {
35
freq += map.get(val).freq;
36
}
37
map.put(val, new Node(val, freq, c));
38
pq.add(new Node(val, freq, c++));
39
}
40

41
public int pop() {
42
Node r = pq.remove();
43
Node a = map.get(r.data);
44
a.freq--;
45
return r.data;
46
}
47
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0