C++ concise two HashSet


  • 0
    B

    one set for good number, one set for used number

    class PhoneDirectory {
    public:
        /** Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        unordered_set<int>used;
        unordered_set<int>good;
        int size, val;
        PhoneDirectory(int maxNumbers) {
            size = maxNumbers;
            val = 0;
        }
        
        /** Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available. */
        int get() {
            int ret = -1;
            if(used.size() == size) return ret;
            if(val < size)
            {
                ret = val;
                val++;
                used.insert(ret);
                good.erase(ret);
            }
            else
            {
                ret = *good.begin();
                good.erase(ret);
                used.insert(ret);
            }
            return ret;
        }
        
        /** Check if a number is available or not. */
        bool check(int number) {
            return used.find(number) == used.end();
        }
        
        /** Recycle or release a number. */
        void release(int number) {
            used.erase(number);
            good.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.