LeetCode Solutions

379. Design Phone Directory

Time: $O(1)$

Space: $O(n)$

			

class PhoneDirectory {
 public:
  /** Initialize your data structure here
      @param maxNumbers - The maximum numbers that can be stored in the phone
     directory. */
  PhoneDirectory(int maxNumbers) : next(maxNumbers) {
    for (int i = 0; i < maxNumbers - 1; ++i)
      next[i] = i + 1;
    next.back() = 0;
  }

  /** Provide a number which is not assigned to anyone.
      @return - Return an available number. Return -1 if none is available. */
  int get() {
    if (next[number] == -1)
      return -1;

    const int ans = number;
    number = next[number];
    next[ans] = -1;  // Mark as used
    return ans;
  }

  /** Check if a number is available or not. */
  bool check(int number) {
    return next[number] != -1;
  }

  /** Recycle or release a number. */
  void release(int number) {
    if (next[number] != -1)
      return;

    next[number] = this->number;
    this->number = number;
  }

 private:
  int number = 0;    // Current possible available number
  vector<int> next;  // Next available number
};
			

class PhoneDirectory {
  /**
   * Initialize your data structure here
   *
   * @param maxNumbers - The maximum numbers that can be stored in the phone
   *                   directory.
   */
  public PhoneDirectory(int maxNumbers) {
    next = new int[maxNumbers];
    for (int i = 0; i < maxNumbers - 1; ++i)
      next[i] = i + 1;
    next[maxNumbers - 1] = 0;
  }

  /**
   * Provide a number which is not assigned to anyone.
   *
   * @return - Return an available number. Return -1 if none is available.
   */
  public int get() {
    if (next[number] == -1)
      return -1;

    final int availableNum = number;
    number = next[number];
    next[availableNum] = -1; // Mark as used
    return ans;
  }

  /** Check if a number is available or not. */
  public boolean check(int number) {
    return next[number] != -1;
  }

  /** Recycle or release a number. */
  public void release(int number) {
    if (next[number] != -1)
      return;

    next[number] = this.number;
    this.number = number;
  }

  private int number; // Current possible available number
  private int[] next; // Next available number
}