forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
43 lines (39 loc) · 1.12 KB
/
Solution.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
class Allocator {
private TreeMap<Integer, Integer> tm = new TreeMap<>();
private Map<Integer, List<Integer>> d = new HashMap<>();
public Allocator(int n) {
tm.put(-1, -1);
tm.put(n, n);
}
public int allocate(int size, int mID) {
int s = -1;
for (var entry : tm.entrySet()) {
int v = entry.getKey();
if (s != -1) {
int e = v - 1;
if (e - s + 1 >= size) {
tm.put(s, s + size - 1);
d.computeIfAbsent(mID, k -> new ArrayList<>()).add(s);
return s;
}
}
s = entry.getValue() + 1;
}
return -1;
}
public int free(int mID) {
int ans = 0;
for (int s : d.getOrDefault(mID, Collections.emptyList())) {
int e = tm.remove(s);
ans += e - s + 1;
}
d.remove(mID);
return ans;
}
}
/**
* Your Allocator object will be instantiated and called as such:
* Allocator obj = new Allocator(n);
* int param_1 = obj.allocate(size,mID);
* int param_2 = obj.free(mID);
*/