【LeetCode刷题笔记-75 705:设计哈希集合】

题目:
在这里插入图片描述
前几天刚学完了STL,今天就来了一道Hash集合题,可以说是很好了,能帮我复习一下知识点。

主要事项如下:

1.哈希表长度的选取要保证为质数。因为这样才能保证哈希表上的每一个位置都被有效运用。

STL里面的哈希表是可以动态增长并且对全部元素做Rehash的,这里我就先不实现了,拿题解里面的质数769来做总长。

2.使用的是链表解决冲突。 STL底层也是使用链表来解决冲突的。

3.hash函数是比较简单的求模

4.其余的没什么好说的,根据哈希表的特性,正常写就行了。

#include<iostream>
#include<vector>
#include<list>

using namespace std;

class MyHashSet {
public:
    vector<list<int>> Hashmap;//使用链表解决冲突 
    static const int Base = 769;
    
    static int hashfunc(int num){
    	return num%Base;
	}
    
    MyHashSet():Hashmap(Base) { 

    }
    
    void add(int key) {
		int h = hashfunc(key);
		for(auto it = Hashmap[h].begin();it!=Hashmap[h].end();it++){
			if((*it)==key){
				return;
			}
		}
		Hashmap[h].push_back(key);
    }
    
    void remove(int key) {
		int h = hashfunc(key);
		for(auto it = Hashmap[h].begin();it!=Hashmap[h].end();i++){
			if((*it)==key){
				Hashmap[h].erase(it);//这个操作会使迭代器失效,要注意使用了erase以后不能继续操作迭代器了
				return; 
			}
		}
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
		int h = hashfunc(key);
		for(auto it = Hashmap[h].begin();it!=Hashmap[h].end();i++){
			if((*it)==key){
				return true;
			}
		}
		return false;
    }
};

int main(){
	MyHashSet myHashSet;
	for(int i=0;i<10;i++)
	{
		myHashSet.add(i);
	}
	
	//这里开始自己调试 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值