379 Design Phone Directory

1. Question

Design a Phone Directory which supports the following operations:
  1. 1.
    get: Provide a number which is not assigned to anyone.
  2. 2.
    check: Check if a number is available or not.
  3. 3.
    release: Recycle or release a number.
Example:
1
// Init a phone directory containing a total of 3 numbers: 0, 1, and 2.
2
PhoneDirectory directory = new PhoneDirectory(3);
3
4
// It can return any available phone number. Here we assume it returns 0.
5
directory.get();
6
7
// Assume it returns 1.
8
directory.get();
9
10
// The number 2 is available, so return true.
11
directory.check(2);
12
13
// It returns 2, the only number that is left.
14
directory.get();
15
16
// The number 2 is no longer available, so return false.
17
directory.check(2);
18
19
// Release number 2 back to the pool.
20
directory.release(2);
21
22
// Number 2 is available again, return true.
23
directory.check(2);
Copied!

2. Implementation

1
class PhoneDirectory {
2
Set<Integer> usedNumbers;
3
Queue<Integer> phoneNumbers;
4
int max;
5
6
/** Initialize your data structure here
7
@param maxNumbers - The maximum numbers that can be stored in the phone directory. */
8
public PhoneDirectory(int maxNumbers) {
9
max = maxNumbers;
10
usedNumbers = new HashSet<>();
11
phoneNumbers = new LinkedList<>();
12
13
for (int i = 0; i < max; i++) {
14
phoneNumbers.add(i);
15
}
16
}
17
18
/** Provide a number which is not assigned to anyone.
19
@return - Return an available number. Return -1 if none is available. */
20
public int get() {
21
if (phoneNumbers.size() <= 0) {
22
return -1;
23
}
24
int number = phoneNumbers.remove();
25
usedNumbers.add(number);
26
return number;
27
}
28
29
/** Check if a number is available or not. */
30
public boolean check(int number) {
31
if (number >= max || number < 0) {
32
return false;
33
}
34
return !usedNumbers.contains(number);
35
}
36
37
/** Recycle or release a number. */
38
public void release(int number) {
39
if (usedNumbers.remove(number)) {
40
phoneNumbers.add(number);
41
}
42
}
43
}
44
45
/**
46
* Your PhoneDirectory object will be instantiated and called as such:
47
* PhoneDirectory obj = new PhoneDirectory(maxNumbers);
48
* int param_1 = obj.get();
49
* boolean param_2 = obj.check(number);
50
* obj.release(number);
51
*/
Copied!

3. Time & Space Complexity

时间复杂度get: O(1), check: O(1), release: O(1), 空间复杂度O(n)