[LeetCode] Design Phone Directory

379. Design Phone Directory

Design a phone directory that initially has maxNumbers empty slots that can store numbers. The directory should store numbers, check if a certain slot is empty or not, and empty a given slot.

Implement the PhoneDirectory class:

  • PhoneDirectory(int maxNumbers) Initializes the phone directory with the number of available slots maxNumbers.
  • int get() Provides a number that is not assigned to anyone. Returns -1 if no number is available.
  • bool check(int number) Returns true if the slot number is available and false otherwise.
  • void release(int number) Recycles or releases the slot number.
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

class PhoneDirectory {
unordered_set<int> released;
int ma;
int mi;
public:
PhoneDirectory(int maxNumbers):ma(maxNumbers), mi(0) {
}

int get() {
if(!released.empty()) {
int n = *released.begin();
released.erase(released.begin());
return n;
} else {
if(mi == ma) return -1;
return mi++;
}
}

bool check(int number) {
if(number >= mi) return true;
return released.count(number);
}

void release(int number) {
if(number < mi)
released.insert(number);
}
};

/**
* Your PhoneDirectory object will be instantiated and called as such:
* PhoneDirectory* obj = new PhoneDirectory(maxNumbers);
* int param_1 = obj->get();
* bool param_2 = obj->check(number);
* obj->release(number);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/20/PS/LeetCode/design-phone-directory/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.