class Allocator {
public:
Allocator(int n) {
}
int allocate(int size, int mID) {
}
int free(int mID) {
}
};
/**
* 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);
*/
from sortedcontainers import SortedList
class Allocator:
def __init__(self, n: int):
self.sl = SortedList([(-1, 1, -1), (n, 1, -1)])
def allocate(self, size: int, I: int) -> int:
for (lp, ln, _), (rp, _, _) in pairwise(self.sl):
if rp - (lp + ln) >= size:
self.sl.add((lp + ln, size, I))
return lp + ln
return -1
def free(self, I: int, res=0) -> int:
remove = [(i, n) for i, (_, n, id) in enumerate(self.sl) if id == I]
while remove:
i, n = remove.pop()
res += n
self.sl.pop(i)
return res
# Your Allocator object will be instantiated and called as such:
# obj = Allocator(n)
# param_1 = obj.allocate(size,mID)
# param_2 = obj.free(mID)
type Allocator []int
func Constructor(n int) Allocator {
return make([]int, n)
}
func (a Allocator) Allocate(size, mID int) int {
cnt := 0
for i, id := range a {
if id > 0 {
cnt = 0
} else if cnt++; cnt == size {
for j := i; j > i-size; j-- {
a[j] = mID
}
return i - size + 1
}
}
return -1
}
func (a Allocator) Free(mID int) (ans int) {
for i, id := range a {
if id == mID {
ans++
a[i] = 0
}
}
return
}
/**
* Your Allocator object will be instantiated and called as such:
* obj := Constructor(n);
* param_1 := obj.Allocate(size,mID);
* param_2 := obj.Free(mID);
*/