-
-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathFreqStack.java
81 lines (66 loc) · 1.67 KB
/
FreqStack.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
package problems.hard;
import java.util.*;
public class FreqStack {
PriorityQueue<Pair> q;
Map<Integer, Pair> map;
int index = -1;
public FreqStack() {
q = new PriorityQueue<>();
map = new HashMap<>();
}
public void push(int x) {
index++;
Pair pair = map.getOrDefault(x, new Pair(x));
pair.add(index);
map.put(x, pair);
q.remove(pair);
q.add(pair);
}
public int pop() {
Pair pair = q.remove();
pair.decrement();
if (pair.count <= 0) {
map.remove(pair.val);
} else {
q.add(pair);
}
return pair.val;
}
class Pair implements Comparable<Pair> {
int val;
int count;
List<Integer> list = new ArrayList<>();
public Pair(int val) {
this.val = val;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair pair = (Pair) o;
return val == pair.val;
}
void add(int index) {
count++;
list.add(index);
}
void decrement() {
count--;
list.remove(list.size() - 1);
}
@Override
public int hashCode() {
return val;
}
@Override
public int compareTo(Pair o) {
if (count > o.count)
return -1;
if (count < o.count)
return 1;
return o.list.get(o.list.size() - 1) - list.get(list.size() - 1);
}
}
}