ID | Title | Difficulty | |
---|---|---|---|
Loading... |
379. Design Phone Directory
Medium
LeetCode
Array, Hash Table, Linked List, Design, Queue
Problem
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);
Code
class PhoneDirectory {
HashSet<Integer> set;
Queue<Integer> queue;
public PhoneDirectory(int maxNumbers) {
set = new HashSet<>();
queue = new LinkedList<>();
for(int i = 0; i < maxNumbers; i++){
set.add(i);
queue.add(i);
}
}
public int get() {
if(queue.size() != 0){
int num = queue.poll();
set.remove(num);
return num;
} else {
return -1;
}
}
public boolean check(int number) {
return set.contains(number);
}
public void release(int number) {
if(set.add(number)){
queue.offer(number);
}
}
}
class PhoneDirectory {
int maxNumbers;
HashSet<Integer> set;
public PhoneDirectory(int maxNumbers) {
this.maxNumbers = maxNumbers;
// set中放已经在用的数字
set = new HashSet<>();
}
public int get() {
for(int i = 0; i < maxNumbers; i++) {
if(!set.contains(i)) {
set.add(i);
return i;
}
}
return -1;
}
public boolean check(int number) {
return !set.contains(number);
}
public void release(int number) {
if(set.contains(number)) {
set.remove(number);
}
}
}
按 <- 键看上一题!
378. Kth Smallest Element in a Sorted Matrix
按 -> 键看下一题!
380. Insert Delete GetRandom O(1)