栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

705~706. 设计哈希集合/哈希映射

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

705~706. 设计哈希集合/哈希映射

705. 设计哈希集合

题目链接

实现
#pragma once
#include 
#include
#include

using namespace std;

class MyHashSet 
{
public:
	//散列函数
	int Hash(int key)
	{
		return key % base;
	}

	MyHashSet() 
	{
		//初始化
		HT.resize(base);
	}

	void add(int key) 
	{

		int index = Hash(key);
		list::iterator it;
		//不添加重复值
		for (it = HT[index].begin(); it != HT[index].end(); it++)
		{
			if ((*it) == key)
			{
				return;
			}
		}
		HT[index].push_back(key);
	}

	void remove(int key)
	{
		int index = Hash(key);
		list::iterator it;
		for (it = HT[index].begin(); it != HT[index].end(); it++)
		{
			if ((*it) == key)
			{
				HT[index].erase(it);
				return;
			}
		}

	}

	bool contains(int key)
	{
		int index = Hash(key);
		list::iterator it;
		for (it = HT[index].begin(); it != HT[index].end(); it++)
		{
			if ((*it) == key)
			{
				return true;
			}
		}
		return false;

	}


public:
	vector> HT;
	int base = 769;
};



int main()
{

	MyHashSet myHashSet;

	myHashSet.add(1);
	myHashSet.add(2);
	cout << myHashSet.contains(1) << endl;
	cout << myHashSet.contains(3) << endl;
	myHashSet.add(2);
	cout << myHashSet.contains(2) << endl;
	myHashSet.remove(2);
	cout << myHashSet.contains(2) << endl;
	myHashSet.add(1000000);
	cout << myHashSet.contains(1000000) << endl;

	system("pause");
	return 0;
}

运行结果

提交结果

706. 设计哈希映射 题目描述

题目链接

实现

设计哈希集合与哈希映射的方法类似:
哈希集合类型:vector
哈希映射类型:vector>>

class MyHashMap
{
public:
	//散列函数
	int Hash(int key)
	{
		return key % base;
	}

	MyHashMap()
	{
		//初始化
		HT.resize(base);
	}

	void put(int key, int value)
	{

		int index = Hash(key);
		list>::iterator it;
		
		for (it = HT[index].begin(); it != HT[index].end(); it++)
		{
			if ((*it).first == key)
			{
				(*it).second = value;
				return;
			}
		}
		HT[index].push_back(make_pair(key,value));
	}


	int get(int key) 
	{
		int index = Hash(key);
		list>::iterator it;
		for (it = HT[index].begin(); it != HT[index].end(); it++) 
		{
			if ((*it).first == key) 
			{
				return (*it).second;
			}
		}
		return -1;
	}


	void remove(int key)
	{
		int index = Hash(key);
		list>::iterator it;
		for (it = HT[index].begin(); it != HT[index].end(); it++)
		{
			if ((*it).first == key)
			{
				HT[index].erase(it);
				return;
			}
		}

	}

public:
	vector>> HT;
	int base = 769;
};
提交结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648916.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号