379. 电话目录管理系统 🔒
379. 电话目录管理系统 🔒
🟠 🔖 设计
队列
数组
哈希表
链表
🔗 力扣
LeetCode
题目
Design a phone directory that initially has maxNumbers
empty slots that can store numbers. The directory should store numbers, check if a certain slot is empty or not, and empty a given slot.
Implement the PhoneDirectory
class:
PhoneDirectory(int maxNumbers)
Initializes the phone directory with the number of available slotsmaxNumbers
.int get()
Provides a number that is not assigned to anyone. Returns-1
if no number is available.bool check(int number)
Returnstrue
if the slotnumber
is available andfalse
otherwise.void release(int number)
Recycles or releases the slotnumber
.
Example 1:
Input
["PhoneDirectory", "get", "get", "check", "get", "check", "release", "check"]
[[3], [], [], [2], [], [2], [2], [2]]
Output
[null, 0, 1, true, 2, false, null, true]
Explanation
PhoneDirectory phoneDirectory = new PhoneDirectory(3);
phoneDirectory.get(); // It can return any available phone number. Here we assume it returns 0.
phoneDirectory.get(); // Assume it returns 1.
phoneDirectory.check(2); // The number 2 is available, so return true.
phoneDirectory.get(); // It returns 2, the only number that is left.
phoneDirectory.check(2); // The number 2 is no longer available, so return false.
phoneDirectory.release(2); // Release number 2 back to the pool.
phoneDirectory.check(2); // Number 2 is available again, return true.
Constraints:
1 <= maxNumbers <= 10^4
0 <= number < maxNumbers
- At most
2 * 10^4
calls will be made to get, check, and release.
题目大意
要求设计一个电话目录管理系统,包含以下两个操作:
get()
:分配一个未被使用的电话号码,返回其编号,如果没有未被使用的号码,则返回-1
。check(number)
:检查指定的电话号码是否被使用。release(number)
:释放一个已经被使用的电话号码。
解题思路
这个问题可以通过维护一个可用号码集合和已使用号码集合来实现,可以使用两个数据结构:
- 一个
Set
存储可用的号码,初始时包含所有可能的号码。 - 一个
Set
存储已经被使用的号码,初始时为空。
通过两个 Set
来分别管理可用和已使用的号码,实现了分配、检查和释放号码的功能。
代码
class PhoneDirectory {
constructor(maxNumbers) {
this.available = new Set();
this.used = new Set();
for (let i = 0; i < maxNumbers; i++) {
this.available.add(i);
}
}
get() {
if (this.available.size == 0) return -1;
const num = this.available.values().next().value;
this.available.delete(num);
this.used.add(num);
return num;
}
check(number) {
return !this.used.has(number);
}
release(number) {
if (this.used.has(number)) {
this.used.delete(number);
this.available.add(number);
}
}
}
相关题目
题号 | 标题 | 题解 | 标签 | 难度 |
---|---|---|---|---|
1845 | 座位预约管理系统 | 设计 堆(优先队列) |