C++ solution using one set


  • 0
    Z
    class PhoneDirectory {
    public:
        /** Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        int maxnum;
        unordered_set<int> avail;
        PhoneDirectory(int maxNumbers) {
            maxnum = maxNumbers;
            for(int i=0;i<maxNumbers;i++){
                avail.insert(i);
            }
        }
        
        /** Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available. */
        int get() {
            if(avail.empty())return -1;
            int tmp = *avail.begin();
            avail.erase(tmp);
            return tmp;
        }
        
        /** Check if a number is available or not. */
        bool check(int number) {
            return avail.count(number);
        }
        
        /** Recycle or release a number. */
        void release(int number) {
            avail.insert(number);
        }
    };
    
    /**
     * Your PhoneDirectory object will be instantiated and called as such:
     * PhoneDirectory obj = new PhoneDirectory(maxNumbers);
     * int param_1 = obj.get();
     * bool param_2 = obj.check(number);
     * obj.release(number);
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.