[LeetCode] Design Phone Directory 設計電話目錄
阿新 • • 發佈:2018-12-27
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);
又是一道設計題,讓我們設計一個電話目錄管理系統,可以分配電話號碼,查詢某一個號碼是否已經被使用,釋放一個號碼,需要注意的是,之前釋放的號碼下一次應該被優先分配。這題對C++解法的時間要求非常苛刻,嘗試了好幾種用set,或者stack/queue,或者使用vector的push_back等等,都TLE了,終於找到了一種可以通過OJ的解法。這裡用兩個一維陣列recycle和flag,分別來儲存被回收的號碼和某個號碼的使用狀態,還有變數max_num表示最大數字,next表示下一個可以分配的數字,idx表示recycle陣列中可以被重新分配的數字的位置,然後在get函式中,沒法分配的情況是,當next等於max_num並且index小於等於0,此時返回-1。否則我們先看recycle裡有沒有數字,有的話先分配recycle裡的數字,沒有的話再分配next。記得更新相對應的flag中的使用狀態,參見程式碼如下:
class PhoneDirectory { public: /** Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ PhoneDirectory(int maxNumbers) { max_num = maxNumbers; next = idx = 0; recycle.resize(max_num); flag.resize(max_num,1); } /** Provide a number which is not assigned to anyone. @return - Return an available number. Return -1 if none is available. */ int get() { if (next == max_num && idx <= 0) return -1; if (idx > 0) { int t = recycle[--idx]; flag[t] = 0; return t; } flag[next] = false; return next++; } /** Check if a number is available or not. */ bool check(int number) { return number >= 0 && number < max_num && flag[number]; } /** Recycle or release a number. */ void release(int number) { if (number >= 0 && number < max_num && !flag[number]) { recycle[idx++] = number; flag[number] = 1; } } private: int max_num, next, idx; vector<int> recycle, flag; };
參考資料: