#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <queue>
#include <string>
#include <map>
using namespace std;
//
// test.h
// test
//
// Created by 吴珝君 on 2018/12/31.
// Copyright © 2018年 闲着也是贤者. All rights reserved.
//
/************************************************************************/
/*
*/
//图的存储--邻接表
#define MAXSIZE 100
#define INF 65535
/************************************************************************/
void swap(int *arr,int L,int R)
{
int temp = arr[L];
arr[L] = arr[R];
arr[R] = temp;
}
//重要问题
int * generateRandomArray(int maxSize, int maxValue,int *size)
{
*size = rand()%maxSize + 1;//产生数组大小
int* arr = new int[*size];//产生1-maxvalue个元素的数组
for (int i = 0; i < *size; i++) {
arr[i] = (int) ( rand()%maxValue) - (int) (rand()%maxValue);//产生随机值
}
return arr;
}
/*
*/
/************************************************************************/
/************************************************************************/
/*
设计RandomPool结构 【题目】 设计一种结构,在该结构中有如下三个功能:
insert(key):将某个key加入到该结构,做到不重复加入。
delete(key):将原本在结构中的某个key移除。
getRandom(): 等概率随机返回结构中的任何一个key。
【要求】 Insert、delete和getRandom方法的时间复杂度都是 O(1 */
/************************************************************************/
class RandomPool
{
public:
RandomPool()
{
size = 0;
}
void inserts(string key)
{
if (keyvalue.count(key) == 0)
{
keyvalue.insert(pair<string, int>(key,size));
valuekey.insert(pair< int, string>(size++, key));
}
}
void deletes(string key)
{
if (keyvalue.count(key) >0)
{
int d = keyvalue.find(key)->second;//找到要删除的位置
string lastvalue = valuekey.find(size - 1)->second;
//将最后一个位置和待删除位置替换
keyvalue.insert(pair<string,int>(lastvalue, d));
valuekey.insert(pair<int,string>(d,lastvalue));//如果是最后一个位置元素要删除也是一样的
size--;
}
}
string getRandom()
{
if (size > 0)
{
int d = rand()%size;
return valuekey.find(d)->second;
}
return NULL;
}
private:
int size;//存储元素个数
map<string, int> keyvalue;
map<int, string> valuekey;
};
int main()
{
RandomPool r;
r.inserts("A");
r.inserts("A");
r.inserts("C");
r.inserts("D");
for (int i = 0 ;i<100; i++)
{
cout<< r.getRandom();
}
r.deletes("D");
for (int i = 0 ;i<100; i++)
{
cout<< r.getRandom();
}
system("pause");
return 0;
}