379. Design Phone Directory

Design a Phone Directory which supports the following operations:

 

  1. get: Provide a number which is not assigned to anyone.
  2. check: Check if a number is available or not.
  3. 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]

Rust Solution

use std::collections::HashSet;

struct PhoneDirectory {
    available: HashSet<i32>,
}

impl PhoneDirectory {
    fn new(max_numbers: i32) -> Self {
        let available = (0..max_numbers).collect();
        PhoneDirectory { available }
    }

    fn get(&mut self) -> i32 {
        if let Some(&x) = self.available.iter().next() {
            self.available.remove(&x);
            x
        } else {
            -1
        }
    }

    fn check(&self, number: i32) -> bool {
        self.available.contains(&number)
    }

    fn release(&mut self, number: i32) {
        self.available.insert(number);
    }
}

#[test]
fn test() {
    let mut obj = PhoneDirectory::new(1);
    assert_eq!(obj.get(), 0);
    assert_eq!(obj.check(0), false);
    assert_eq!(obj.get(), -1);
    obj.release(2);
    assert_eq!(obj.check(2), true);
}

Having problems with this solution? Click here to submit an issue on github.