3659 · Design Phone Directory
Algorithms
Easy
Description
In this question, you need to design a phone directory management system class.
The constructor of the telephone directory management system will receive a variable maxNumbers of integer type, which represents the maximum number of the telephone directory.
In addition to the constructor, you also need to design the following functions in this class reasonably:
int get(): Get the next available number in the phone directory, or return -1 if there is no available number
bool check(int number): Check if the specified number is available
void release(int number): Modify the status of a number to be available
Only $39.9 for the “Twitter Comment System Project Practice” within a limited time of 7 days!
WeChat Notes Twitter for more information(WeChat ID jiuzhang104)
The range of available numbers is from 0 to maxNumbers, not including maxNumbers.
You need to assign according to the value of the number from small to large.
Example
Example 1
Input:
3
[“get()”, “check(0)”, “get()”, “get()”, “release(2)”, “check(2)”, “get()”, “check(2)”]
Output:
[0, false, 1, 2, null, true, 2, false]
Example 2
Input:
0
[“get()”, “check(0)”, “release(0)”]
Output:
[-1, false, null]
解法1:用set。注意不能用unordered_set,因为get()必须是下一个可以用的号码,有顺序要求的。
class PhoneDirectory {
public:
PhoneDirectory(int maxNumbers) {
this->maxNumbers = maxNumbers;
for (int number = 0; number < maxNumbers; number++) {
unused.insert(number);
}
}
/**
* @return: the available number of the phone directory
*/
int get() {
if (!unused.empty()) {
int number = *unused.begin();
unused.erase(number);
return number;
}
return -1;
}
/**
* @param number: the number to be checked
* @return: check whether the number of the phone directory is available
*/
bool check(int number) {
if (unused.find(number) != unused.end()) return true;
return false;
}
/**
* @param number: the number of the phone directory to be released
* @return: nothing
*/
void release(int number) {
unused.insert(number);
}
private:
int maxNumbers;
set<int> unused;
};
博客围绕设计电话目录管理系统类展开,该系统构造函数接收最大号码数,还需设计get、check、release函数。介绍了可用号码范围及分配规则,给出示例输入输出,还提及一种用set的解法,强调不能用unordered_set。
2万+

被折叠的 条评论
为什么被折叠?



