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.
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);
又是一道設計題,讓我們設計一個電話目錄管理系統,可以分配電話號碼,查詢某一個號碼是否已經被使用,釋放一個號碼。既然要分配號碼,肯定需要一個數組 nums 來存所有可以分配的號碼,注意要初始化成不同的數字。然后再用一個長度相等的數組 used 來標記某個位置上的號碼是否已經被使用過了,用一個變量 idx 表明當前分配到的位置。再 get 函數中,首先判斷若 idx 小於0了,說明沒有號碼可以分配了,返回 -1。否則就取出 nums[idx],並且標記該號碼已經使用了,注意 idx 還要自減1,返回之前取出的號碼。對於 check 函數,直接在 used 函數中看對應值是否為0。最后實現 release 函數,若該號碼沒被使用過,直接 return;否則將 idx 自增1,再將該號碼賦值給 nums[idx],然后在 used 中標記為0即可,參見代碼如下:
解法一:
class PhoneDirectory { public: PhoneDirectory(int maxNumbers) { nums.resize(maxNumbers); used.resize(maxNumbers); idx = maxNumbers - 1; iota(nums.begin(), nums.end(), 0); } int get() { if (idx < 0) return -1; int num = nums[idx--]; used[num] = 1; return num; } bool check(int number) { return used[number] == 0; } void release(int number) { if (used[number] == 0) return; nums[++idx] = number; used[number] = 0; } private: int idx; vector<int> nums, used; };
我們也可以使用隊列 queue 和 HashSet 來做,整個思想和上面沒有啥太大的區別,就是寫法上略有不同,參見代碼如下:
解法二:
class PhoneDirectory { public: PhoneDirectory(int maxNumbers) { mx = maxNumbers; for (int i = 0; i < maxNumbers; ++i) q.push(i); } int get() { if (q.empty()) return -1; int num = q.front(); q.pop(); used.insert(num); return num; } bool check(int number) { return !used.count(number); } void release(int number) { if (!used.count(number)) return; used.erase(number); q.push(number); } private: int mx; queue<int> q; unordered_set<int> used; };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/379
參考資料:
https://leetcode.com/problems/design-phone-directory/
