LintCode 3659 · Design Phone Directory (set设计题)

博客围绕设计电话目录管理系统类展开,该系统构造函数接收最大号码数,还需设计get、check、release函数。介绍了可用号码范围及分配规则,给出示例输入输出,还提及一种用set的解法,强调不能用unordered_set。

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;
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值