379. Design Phone Directory

Design a Phone Directory which supports the following operations:
get: Provide a number which is not assigned to anyone.
check: Check if a number is available or not.
release: Recycle or release a number.
Example:

// Init a phone directory containing a total of 3 numbers: 0, 1, and 2.
PhoneDirectory directory = new PhoneDirectory(3);

// It can return any available phone number. Here we assume it returns 0.
directory.get();

// Assume it returns 1.
directory.get();

// The number 2 is available, so return true.
directory.check(2);

// It returns 2, the only number that is left.
directory.get();

// The number 2 is no longer available, so return false.
directory.check(2);

// Release number 2 back to the pool.
directory.release(2);

// Number 2 is available again, return true.
directory.check(2);

Solution1:Queue + Hashset

思路: queue for getting, and hashmap for checking
Time Complexity: O(1) Space Complexity: O(N)

Solution2:只用一个Hashset?个人认为不行

思路:如果只用set的话,get用:set的遍历
Controversy:有可能set遍历,即使是get1个的话也可能是O(N)的 想象遍历bucket一样

Hashset: This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important

HashSet is imlemented using a HashMap where the elements are the map keys. Since a map has a defined number of buckets that can contain one or more elements, iteration needs to check each bucket, whether it contains elements or not.

Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

class PhoneDirectory {

    /** Initialize your data structure here
        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
    Set used;
    Queue available;
    
    public PhoneDirectory(int maxNumbers) {
        used = new HashSet();
        available = new LinkedList();
        
        for(int i = 0; i < maxNumbers; i++) {
            available.offer(i);
        }    
    }
    
    /** Provide a number which is not assigned to anyone.
        @return - Return an available number. Return -1 if none is available. */
    public int get() {
        Integer ret = available.poll();
        if(ret == null) return -1;
        used.add(ret);
        return ret;
    }
    
    /** Check if a number is available or not. */
    public boolean check(int number) {
        return !used.contains(number);
    }
    
    /** Recycle or release a number. */
    public void release(int number) {
        if(used.remove(number)) {
            available.offer(number);
        }
    }
}

你可能感兴趣的:(379. Design Phone Directory)