java: array + queue(375ms)


  • 0
    public class PhoneDirectory {
    
        /** Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        int[] map;
        LinkedList<Integer> queue = new LinkedList<Integer>();
        public PhoneDirectory(int maxNumbers) {
            map = new int[maxNumbers];
            for(int i = 0 ; i < maxNumbers ; i++) {
                queue.offer(i);
                map[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(queue.isEmpty()) return -1;
            int index = queue.poll();
            map[index]--;
            return index;
        }
        
        /** Check if a number is available or not. */
        public boolean check(int number) {
            return map[number] == 1;
        }
        
        /** Recycle or release a number. */
        public void release(int number) {
            if(map[number] == 1) {
                return;
            }
            map[number]++;
            queue.offer(number);
        }
    }
    
    /**
     * Your PhoneDirectory object will be instantiated and called as such:
     * PhoneDirectory obj = new PhoneDirectory(maxNumbers);
     * int param_1 = obj.get();
     * boolean 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.