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); } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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