Java AC solution uses array and LinkedList( beats 100% submissions)


  • 0
    P
    class PhoneDirectory {
       boolean[] numbers;
        LinkedList<Integer> available;
        /** Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        public PhoneDirectory(int maxNumbers) {
            numbers=new boolean[maxNumbers];
            available = new LinkedList<>();
            for(int i=0; i<maxNumbers; i++)
                available.add(i);
        }
        
        /** Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available. */
        public int get() {
            if(available.isEmpty())
                return -1;
            int top =available.poll();
            numbers[top]=true;
            return top;
        }
        
        /** Check if a number is available or not. */
        public boolean check(int number) {
             if(number<0 || number>=numbers.length)
                 return false;
            return numbers[number]==false;
        }
        
        /** Recycle or release a number. */
        public void release(int number) {
            if(number<0 || number>=numbers.length||numbers[number]==false)
                return;
            numbers[number]=false;
            available.add(number);
        }
    }
    

Log in to reply
 

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