Java AC Solution using set, beats 100%


  • 1
    T

    class PhoneDirectory {

    /** Initialize your data structure here
        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
    Set<Integer> s;
    int max;
    int min;
    public PhoneDirectory(int maxNumbers) {
        s = new HashSet<>();
        for (int i = 0; i < maxNumbers; i ++)
            s.add(i);
        max = maxNumbers - 1;
        min = 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 (s.size() == 0)
            return -1;
        int res = s.iterator().next();
        s.remove(res);
        return res;
    }
    
    /** Check if a number is available or not. */
    public boolean check(int number) {
        if (number < min || number > max)
            return false;
        return s.contains(number);
    }
    
    /** Recycle or release a number. */
    public void release(int number) {
        s.add(number);
    }
    

    }


Log in to reply
 

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