# 379 Design Phone Directory

設計一個電話簿程式,功能包括分配電話號碼給人,確認此電話號碼有沒有人用,還有把不用的電話號碼回收。

用一個HashSet used來存已經有人使用的號碼,用一個queue來存還沒有人用的號碼,

並且要注意電話簿有號碼數量上限。

  • Constructor: 把0~max加入queue
  • get(): 從queue中poll出一個可用號碼,並將此號碼加入used,若queue中沒有可用號碼就return -1
  • check(): 看此號碼有沒有在used中
  • release(): remove from used, and add to queue
public class PhoneDirectory {
//**need to consider max**
//use a hashset to save the phone numbers that have been used.
//use a queue to save available phone numbers
Set<Integer> used = new HashSet<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
int max;
    /** Initialize your data structure here
        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
    public PhoneDirectory(int maxNumbers) {
        //initialize the queue, put available numbers inside
        for(int i=0; i<maxNumbers; i++){
            queue.add(i);
        }
        max = maxNumbers;

    }

    /** Provide a number which is not assigned to anyone.
        @return - Return an available number. Return -1 if none is available. */
    public int get() {
        //get a number from queue
        //put this number into hashset
        Integer num = queue.poll();
        if(num!=null){
            used.add(num);
            return num;
        }
        else    return -1;
    }

    /** Check if a number is available or not. */
    public boolean check(int number) {
        //check if number exists in hashset
        if(number>=0 && number <=max)
            return !used.contains(number);
        else return false;
    }

    /** Recycle or release a number. */
    public void release(int number) {
        //remove number from hashset
        //put number into queue
        if(used.remove(number))
            queue.add(number);
    }
}

/**
 * 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);
 */

results matching ""

    No results matching ""