Fast Java solution storing only free numbers


  • 0
    M
    public class PhoneDirectory {
    private int max;
    private int count;
    private LinkedList<Integer> free;
    private Set<Integer> freeSet;
    
    /** Initialize your data structure here
        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
    public PhoneDirectory(int maxNumbers) {
        max = maxNumbers;
        count = 0;
        free = new LinkedList<>();
        freeSet = new HashSet<>();
    }
    
    /** Provide a number which is not assigned to anyone.
        @return - Return an available number. Return -1 if none is available. */
    public int get() {
        if(count == max) return -1;
        count++;
        if(free.isEmpty())
            return count - 1;
        else {
            Integer ret = free.remove();
            freeSet.remove(ret);
            return ret;
        }
    }
    
    /** Check if a number is available or not. */
    public boolean check(int number) {
        return freeSet.contains(number) || number >= count + free.size();
    }
    
    /** Recycle or release a number. */
    public void release(int number) {
        if(!check(number)) {
            count--;
            free.add(number);
            freeSet.add(number);
        }
    }
    }

Log in to reply
 

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