/
DesignMemoryAllocator.java
69 lines (60 loc) · 1.81 KB
/
DesignMemoryAllocator.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
// https://leetcode.com/problems/design-memory-allocator
class Allocator {
int[] mem;
public Allocator(int n) {
mem = new int[n];
// Store a value in each element
// The value would signify that "Including this element, the next <value> elements are free"
for (int i = n - 1, j = 1; i >= 0; i--, j++) {
mem[i] = j;
}
}
public int allocate(int size, int mID) {
// Find the first index where mem[i] >= size
int allocIndex = -1;
for (int i = 0; i < mem.length; i++) {
if (mem[i] >= size) {
allocIndex = i;
break;
}
}
if (allocIndex >= 0) {
for (int i = allocIndex, j = 0; j < size; j++) {
// Store the id as negative
mem[i + j] = -mID;
}
}
return allocIndex;
}
public int free(int mID) {
int count = 0;
for (int i = 0; i < mem.length; i++) {
if (mem[i] == -mID) {
mem[i] = 0;
count += 1;
}
}
// Re-process the array so that it can tell how many blocks are free
for (int i = mem.length - 1; i >= 0; i--) {
if (i == mem.length - 1) {
if (mem[i] == 0)
mem[i] = 1;
} else {
if (mem[i] >= 0) {
if (mem[i + 1] > 0) {
mem[i] = mem[i + 1] + 1;
} else {
mem[i] = 1;
}
}
}
}
return count;
}
}
/**
* 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);
*/