Problem:
  设计RandomPool结构
  【题目】 设计一种结构,在该结构中有如下三个功能:
    insert(key):将某个key加入到该结构,做到不重复加入。
    delete(key):将原本在结构中的某个key移除。
    getRandom():等概率随机返回结构中的任何一个key。

  【要求】 Insert、delete和getRandom方法的时间复杂度都是O(1)

Solution:
  使用两个hash表,一个是记录标号,一个记录关键词
  这里有个关键之处就是,等概率返回一个关键词
  若简单使用用哈希表来进行存储,那么有个问题,当删除数据时,会使得哈希表中间产生空白数据
  最好的避免中间产生空数据的方法就是将要删除数据的与表中末尾的数据进行交换
  然后直接删除最后的数据,故需要使用两个哈希表

Code:  

 #pragma once
#include <iostream>
#include <hash_map>
#include <string>
#include <time.h>
#include <stdlib.h> using namespace std; template<class T>
class RandomPool
{
public:
void insert(T key);
void del(T key);
T getRandom();
void getPrint(T key);
void getPrint(int index); private:
hash_map<T, int>KeyMap;
hash_map<int, T>IndexMap;
int size = ;
}; template<class T>
void RandomPool<T>::insert(T key)
{
if (KeyMap.find(key) == KeyMap.end())
{
KeyMap[key] = this->size;
IndexMap[this->size] = key;
++(this->size);
cout << "add succeed!" << endl;
}
else
cout << "add filed!" << endl;
} template<class T>
void RandomPool<T>::del(T key)
{
auto ptr = KeyMap.find(key);
if (ptr == KeyMap.end())
{
cout << "delete filed! there is not exsite the key!" << endl;
return;
}
//交换查找到元素与最后一个元素
T temp = IndexMap[--(this->size)];//最后一个元素的关键词,同时将hash表中的元素删除了
int index = KeyMap[key];//要删除元素的位置
KeyMap[temp] = index;
IndexMap[index] = temp;//将最后一个元素替换要删除元素的位置
//正式删除
KeyMap.erase(ptr);
IndexMap.erase(IndexMap.find(index));
} template<class T>
T RandomPool<T>::getRandom()
{
if (this->size == )
{
cout << "the map is empty!" << endl;
}
else
{
int index = (int)((rand() % ( + ) / (double)( + ))*(this->size));//随机生成一个位置
return IndexMap[index];
}
} template<class T>
void RandomPool<T>::getPrint(T key)
{
if (KeyMap.find(key) == KeyMap.end())
cout << "the key is not exsite!" << endl;
else
cout << KeyMap[key] << endl;
} template<class T>
void RandomPool<T>::getPrint(int index)
{
if (IndexMap.find(index) == IndexMap.end())
cout << "the key is not exsite!" << endl;
else
cout << IndexMap[index] << endl;
} void Test()
{
srand((unsigned)time(NULL));
RandomPool<string>map;
map.insert("zz");
map.insert("zw");
map.insert("ww");
map.insert("wz"); cout << map.getRandom() << endl;
map.getPrint();
map.getPrint("ww");
map.del("zw");
map.getPrint("zw");
}

左神算法基础班5_1设计RandomPool结构的更多相关文章

  1. 左神算法基础班4_1&2实现二叉树的先序、中序、后序遍历,包括递归方式和非递归

    Problem: 实现二叉树的先序.中序.后序遍历,包括递归方式和非递归方式 Solution: 切记递归规则: 先遍历根节点,然后是左孩子,右孩子, 根据不同的打印位置来确定中序.前序.后续遍历. ...

  2. 左神算法进阶班5_4设计可以变更的缓存结构(LRU)

    [题目] 设计一种缓存结构,该结构在构造时确定大小,假设大小为K,并有两个功能: set(key, value):将记录(key, value)插入该结构. get(key):返回key对应的valu ...

  3. 左神算法进阶班1_5BFPRT算法

    在无序数组中找到第k大的数1)分组,每N个数一组,(一般5个一组)2)每组分别进行排序,组间不排序3)将每个组的中位数拿出来,若偶数,则拿上 / 下中位数, 成立一个一个新数组.4)新数组递归调用BF ...

  4. 左神算法进阶班3_1构造数组的MaxTree

    题目 一个数组的MaxTree定义: 数组必须没有重复元素 MaxTree是一棵二叉树,数组的每一个值对应一个二叉树节点 包括MaxTree树在内且在其中的每一棵子树上,值最大的节点都是树的头 给定一 ...

  5. 左神算法进阶班1_4Manacher算法

    #include <iostream> #include <string> using namespace std; //使用manacher算法寻找字符中最长的回文子串 in ...

  6. 左神算法进阶班1_1添加最少字符得到原字符N次

    Problem: 给定一个字符串str1,只能往str1的后面添加字符变成str2. 要求1:str2必须包含两个str1,两个str1可以有重合,但是不能以同一个位置开头. 要求2:str2尽量短最 ...

  7. 左神算法进阶班4_2累加和为aim的最长子数组

    [题目] 给定一个数组arr,和一个整数aim,求在arr中,累加和等于num的最长子数组的长度 例子: arr = { 7,3,2,1,1,7,7,7 } aim = 7 其中有很多的子数组累加和等 ...

  8. 左神算法进阶班8_1数组中累加和小于等于aim的最长子数组

    [题目] 给定一个数组arr,全是正数:一个整数aim,求累加和小于等于aim的,最长子数组,要求额外空间复杂度O(1),时间复杂度O(N) [题解] 使用窗口: 双指针,当sum <= aim ...

  9. 左神算法进阶班6_1LFU缓存实现

    [题目] LFU也是一个著名的缓存算法,自行了解之后实现LFU中的set 和 get 要求:两个方法的时间复杂度都为O(1) [题解] LFU算法与LRU算法很像 但LRU是最新使用的排在使用频率最前 ...

随机推荐

  1. bzoj1029题解

    [解题思路] 贪心,先按结束时间排序,从左到右扫描过去,如果当前建筑可以修复则入大根堆,否则,若其修复时间比堆顶小则弹出堆顶并入堆,处理完堆后则更新总时间.复杂度O(nlog2n). [参考代码] # ...

  2. Nginx被动健康检查和主动健康检查

    1.被动健康检查 Nginx自带有健康检查模块:ngx_http_upstream_module,可以做到基本的健康检查,配置如下: upstream cluster{ server max_fail ...

  3. map和unordered_map使用小结

    map和unordered_map unordered_map简介: #include <cstdio> #include <iostream> #include <un ...

  4. 7.RabbitMQ RFC同步调用

    RabbitMQ RFC同步调用是使用了两个异步调用完成的,生产者调用消费者的同时,自己也作为消费者等待某一队列的返回消息,消费者接受到生产者的消息同时,也作为消息发送者发送一消息给生产者.参考下图: ...

  5. Python-爬虫-HTTP协议请求之GET请求

    我们在百度搜索时,输入关键词,比如“hello”,URL发生变化,如下: https://www.baidu.com/s?wd=hello&rsv_spt=1&rsv_iqid=0xf ...

  6. 微信-小程序-开发文档-服务端-模板消息:templateMessage.send

    ylbtech-微信-小程序-开发文档-服务端-模板消息:templateMessage.send 1.返回顶部 1. templateMessage.send 本接口应在服务器端调用,详细说明参见服 ...

  7. Day 12 :迭代器与生成器

    可迭代:在Python中如果一个对象有__iter__( )方法,则称这个对象是可迭代的(Iterable): 其中__iter__( )方法的作用是让对象可以用for ... in循环遍历,列表Li ...

  8. linux centos 装g++安装不了

    今天需要编译一个项目的时候在装g++都装不上, [root@master hadoop]# yum install g++ Loaded plugins: fastestmirror, refresh ...

  9. Pathfinding 模板题 /// BFS oj21413

    题目大意: Description Bessie is stranded on a deserted arctic island and wants to determine all the path ...

  10. WinDbg神断点

    https://blogs.msdn.microsoft.com/alejacma/2007/10/31/cryptoapi-tracer-script/ 我得多少年才能学会这种写法.