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);
题解:由于get,release,check方法调用次数很多。用STLmap容器,因为会扩容,会超时。改用数组就好。
class PhoneDirectory {
public:
/** Initialize your data structure here
@param maxNumbers - The maximum numbers that can be stored in the phone directory. */
PhoneDirectory(int maxNumbers) {
maxx=maxNumbers;
head=new node(-1);
node *pre=head;
Map=new bool[maxNumbers];
for(int i=0;i<maxNumbers;i++) {
pre->next=new node(i);
pre=pre->next;
Map[i]=true;
}
}
/** Provide a number which is not assigned to anyone.
@return - Return an available number. Return -1 if none is available. */
int get() {
if(head->next==NULL) return -1;
node *cur=head->next;
int top=cur->val;
head->next=cur->next;
Map[top]=false;
delete cur;
return top;
}
/** Check if a number is available or not. */
bool check(int number) {
if(number<0||number>=maxx) return false;
return Map[number];
}
/** Recycle or release a number. */
void release(int number) {
if(number<0||number>=maxx) return ;
if(Map[number]) return;
else {
Map[number]=true;
node *cur=new node(number);
cur->next=head->next;
head->next=cur;
}
}
struct node{
int val;
node* next;
node(int x) {
val=x;next=NULL;
}
};
private:
node* head;
bool* Map;
int maxx;
};
/**
* Your PhoneDirectory object will be instantiated and called as such:
* PhoneDirectory obj = new PhoneDirectory(maxNumbers);
* int param_1 = obj.get();
* bool param_2 = obj.check(number);
* obj.release(number);
*/