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);
Constraints:
1 <= maxNumbers <= 10^4
0 <= number < maxNumbers
- The total number of call of the methods is between
[0 - 20000]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | class PhoneDirectory { int Cap; Set<Integer> set0; Set<Integer> set1; /** Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ public PhoneDirectory(int maxNumbers) { Cap = maxNumbers; set0 = new HashSet<>(); set1 = new HashSet<>(); for(int i=0; i<Cap; ++i) set0.add(i); } /** Provide a number which is not assigned to anyone. @return - Return an available number. Return -1 if none is available. */ public int get() { Iterator<Integer> it = set0.iterator(); if(!it.hasNext()){ return -1; }else{ Integer v = it.next(); set0.remove(v); set1.add(v); return v; } } /** Check if a number is available or not. */ public boolean check(int number) { return set0.contains(number); } /** Recycle or release a number. */ public void release(int number) { set1.remove(number); set0.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); */ |
No comments:
Post a Comment