2502. Design Memory Allocator
Description
You are given an integer n
representing the size of a 0-indexed memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
- Allocate a block of
size
consecutive free memory units and assign it the idmID
. - Free all memory units with the given id
mID
.
Note that:
- Multiple blocks can be allocated to the same
mID
. - You should free all the memory units with
mID
, even if they were allocated in different blocks.
Implement the Allocator
class:
Allocator(int n)
Initializes anAllocator
object with a memory array of sizen
.int allocate(int size, int mID)
Find the leftmost block ofsize
consecutive free memory units and allocate it with the idmID
. Return the block’s first index. If such a block does not exist, return-1
.int freeMemory(int mID)
Free all memory units with the idmID
. Return the number of memory units you have freed.
Example 1:
1 | Input |
Constraints:
1 <= n, size, mID <= 1000
- At most
1000
calls will be made toallocate
andfreeMemory
.
Hints/Notes
- 2025/05/08 Q1
- design
- No solution from 0x3F or Leetcode
Solution
Language: C++
1 | class Allocator { |