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);

分析

1 一个set放released, 一个int记录当前已达数字(++--)

2 一个set装满所有available,加加减减.cons 初始要O(N)

3 java BitSet 和 index。 index就是当前数,release 就clear and set index. get 就 return index and set index

4 segment tree

方法1:

release要有判断,max不可达

方法2:

3 bitset

Space is much efficient: O(c), wouldn’t say it is O(1) because we still need max_size number of bits

这里bit的长度 = max number,某个数字就是设置这个位上的bit

nextClearBit(num)注意此处需要参数

4 segment Tree

O(log n) time in allocate and release

总共2*max个节点,max个叶节点》max,max个内节点 《max。线段树是Bool arr

get取第一个超过max的未赋值,也就是叶节点。 每次使用叶节点或者释放,都要更新内节点。pushup

Last updated

Was this helpful?