算法第五节(第1部分:认识哈希表和哈希函数)

#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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值