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.
// 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);
Setused = new HashSet (); Queue available = new LinkedList (); int max; public PhoneDirectory(int maxNumbers) { max = maxNumbers; for (int i = 0; i < maxNumbers; i++) { available.offer(i); } } public int get() { Integer ret = available.poll(); //Use Integer in case ret is null if (ret == null) { return -1; //Handle null exception } used.add(ret); return ret; } public boolean check(int number) { //Use HashSet only if (number >= max || number < 0) { return false; } return !used.contains(number); } public void release(int number) { //from used to available if (used.remove(number)) { available.offer(number); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/66133.html
摘要:题目链接直接用一个,结果了看了加了个,不过感觉没什么必要加,反正保存的都一样,只是的时间大于,用可以保证。看了题目条件是可以随便返回一个值,但是不让这么做。很无语啊如果这道题要求要求的是的,那就和一样了。 Design Phone Directory 题目链接:https://leetcode.com/problems... 直接用一个set,结果tle了= = public clas...
Problem Design an in-memory file system to simulate the following functions: ls: Given a path in string format. If it is a file path, return a list that only contains this files name. If it is a direc...
摘要:最新更新请见深度优先搜索复杂度时间空间递归栈空间思路首先建一个表,来映射号码和字母的关系。然后对号码进行深度优先搜索,对于每一位,从表中找出数字对应的字母,这些字母就是本轮搜索的几种可能。 Letter Combinations of a Phone Number 最新更新请见:https://yanjia.me/zh/2019/01/... Given a digit string...
摘要:题目要求也就是说,将数字对应的字母的排列组合的的所有可能结果都枚举出来,顺序不唯一。这种类型的题目一般需要求出上一种情况的前提下才可以得知下一种情况。这一种数据结构通过来实现。相比于上一种思路中,内存占用更小,而且更加灵活。 题目要求 Given a digit string, return all possible letter combinations that the numbe...
摘要:而按键和字母的对应关系如上图。这将成为下一次操作的前序字符串。对于每一个不同的前序字符串,我们都要在其后面分别加上当前键所表示的不同字符,再将获得的结果字符串加入里面。 题目详情 Given a digit string, return all possible letter combinations that the number could represent. mapping o...
阅读 3564·2021-11-16 11:45
阅读 2099·2021-11-08 13:23
阅读 2212·2021-10-11 10:59
阅读 2892·2021-09-27 13:36
阅读 2481·2019-08-30 15:54
阅读 2669·2019-08-29 16:58
阅读 2783·2019-08-29 16:56
阅读 1342·2019-08-26 13:52