Java Solution using just one HashSet


  • 0
    public class PhoneDirectory {
    
        int maxNumbers, nextNum;
        Set<Integer> freePool = new HashSet<>();
        
        /** Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        public PhoneDirectory(int maxNumbers) {
            this.maxNumbers = maxNumbers-1;
            this.nextNum = 0;
        }
        
        /** Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available. */
        public int get() {
            if(freePool.size()>0) {
                int val = freePool.iterator().next();
                freePool.remove(val);
                return val;
            }
            if(nextNum<=maxNumbers)
                return nextNum++;
            return -1;
        }
        
        /** Check if a number is available or not. */
        public boolean check(int number) {
            if(number<0 || number>maxNumbers)
                return false;
            if(freePool.contains(number))
                return true;
            else
                return number>=nextNum ? true : false;
        }
        
        /** Recycle or release a number. */
        public void release(int number) {
            if(number>=0 && number<nextNum)
                freePool.add(number);
        }
    }

Log in to reply
 

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