纸上得来终觉浅 绝知此事要躬行

纸上得来终觉浅 绝知此事要躬行

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;
};
10-06 10:11