Java solution beats 99%


  • 1
    Z

    public class PhoneDirectory {

    /** Initialize your data structure here
        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
    boolean[] taken;
    int cur , count;
    Queue<Integer> q;
    
    public PhoneDirectory(int maxNumbers) {
        this.taken = new boolean[maxNumbers];
        this.count = 0;
        this.cur = 0;
        q = new LinkedList<>();
    }
    
    /** Provide a number which is not assigned to anyone.
        @return - Return an available number. Return -1 if none is available. */
    public int get() {
        if(this.cur < taken.length) {
            this.taken[cur] = true;
            count++;
            return cur++;
        } else if(count == taken.length){
           return -1;
        } else {
            if(q.isEmpty()) {
                return -1;
            }
            
            int num = q.poll();
            count--;
            taken[num] = true;
            
            return num;
        }
    }
    
    /** Check if a number is available or not. */
    public boolean check(int number) {
        if(number >= taken.length) {
            return false;
        }
        return !taken[number];
    }
    
    /** Recycle or release a number. */
    public void release(int number) {
        if(number >= taken.length)
            return;
        if(taken[number]) {
            taken[number] = false;
            q.add(number);
            count--;
        }
        
    }
    

    }

    /**

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