设计RandomPool结构
【题目】 设计一种结构, 在该结构中有如下三个功能:insert(key): 将某个key加入到该结构, 做到不重复加入。delete(key): 将原本在结构中的某个key移除。 getRandom():等概率随机返回结构中的任何一个key。
【要求】 Insert、 delete和getRandom方法的时间复杂度都是O(1)
// 设计RandomPool结构.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<map>
#include<string>
#include<cstdlib>
#include <ctime>
using namespace std;
class RandomPool {
private:
map<string, int>keyindexMap;
map<int, string>indexKeyMap;
int size=0;
public:
void insert(string key)
{
if (!this->keyindexMap.count(key))
{
this->keyindexMap[key]=this->size;
this->indexKeyMap[this->size] = key;
this->size++;
}
}
void Delete(string key)
{
if (keyindexMap.count(key))
{
int DeleteIndex = keyindexMap[key];
int LastIndex = --this->size;
string LastKey = indexKeyMap[LastIndex];
indexKeyMap[DeleteIndex] = LastKey;
keyindexMap[LastKey] = DeleteIndex;
keyindexMap.erase(key);
indexKeyMap.erase(LastIndex);
}
}
string getRandow()
{
if (this->size == 0) return nullptr;
int randomIndex = rand()%this->size;
return indexKeyMap[randomIndex];
}
};
int main()
{
RandomPool pool;
pool.insert("zheng");
pool.insert("yun");
pool.insert("tian");
pool.Delete("yun");
string a = pool.getRandow();
string b= pool.getRandow();
string c= pool.getRandow();
string d = pool.getRandow();
cout << a << endl;
cout << b << endl;
cout << c<< endl;
cout << d<< endl;
return 0;
}