Simple method using LinkedHashMap


  • 0
    J
    class PhoneDirectory {
        Map<Integer, Boolean> map;
        /** Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        public PhoneDirectory(int maxNumbers) {
            map = new LinkedHashMap<Integer, Boolean>();
            for (int i=0; i<maxNumbers; i++) {
                map.put(i, true);
            }
        }
        
        /** Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available. */
        public int get() {
            Iterator iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if (entry.getValue().equals(true)){
                    entry.setValue(false);
                    return (int)entry.getKey();
                };
            }
            return -1;
        }
        
        /** Check if a number is available or not. */
        public boolean check(int number) {
            if (map.containsKey(number) && map.get(number) == true) return true;
            return false;
        }
        
        /** Recycle or release a number. */
        public void release(int number) {
            map.put(number, true);
        }
    }
    

Log in to reply
 

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