c++ array+unordered_set solution


  • 0
    T
    class PhoneDirectory {
        unordered_set<int> occupied;
        vector<int> nums;
        int cur_indx, max_num;
    public:
        /** Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        PhoneDirectory(int maxNumbers):max_num(maxNumbers), cur_indx(0) {
            nums.reserve(maxNumbers);
            for (int i = 0; i < max_num; ++i) nums.push_back(i);
        }
        
        /** Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available. */
        int get() {
            if (cur_indx >= max_num) return -1;
            occupied.insert(nums[cur_indx]);
            return nums[cur_indx++];
        }
        
        /** Check if a number is available or not. */
        bool check(int number) {
            return occupied.find(number) == occupied.end();
        }
        
        /** Recycle or release a number. */
        void release(int number) {
            if (occupied.find(number) == occupied.end()) return;
            nums[--cur_indx] = number;
            occupied.erase(number);
        }
    };
    

Log in to reply
 

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