Simple Java solution using LinkedHashSet


  • 0
    A
    class PhoneDirectory {
    // algorithm 2017/09/09: the easist is to use a LinkedHashSet to store pool of available numbers, 
    //  and another pool of used numbers, but the space is O(n)
    // or use two pointers to mark the begin and end of available numbers
    
    /** Initialize your data structure here
        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
    public PhoneDirectory(int maxNumbers) {
        for (int num = 0; num < maxNumbers; num++) {
            availableNumbers.add(num);
        }
    }
    
    /** Provide a number which is not assigned to anyone.
        @return - Return an available number. Return -1 if none is available. */
    public int get() {
        if (availableNumbers.isEmpty()) {
            return -1;
        } else {
            int num = availableNumbers.iterator().next();
            availableNumbers.remove(num);
            return num;
        }
        
    }
    
    /** Check if a number is available or not. */
    public boolean check(int number) {
        return availableNumbers.contains(number);
    }
    
    /** Recycle or release a number. */
    public void release(int number) {
        availableNumbers.add(number);
    }
    
    private Set<Integer> availableNumbers = new LinkedHashSet<>();
    

    }

    /**

    • 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.