设计哈希集合:
题解:vector实现
#define MAX_LEN 100000
class MyHashSet {
private:
//使用数组来实现 vector类型的数组
vector<int> set[MAX_LEN];
//返回某一个key值所属的桶
int getIndex(int key){
//采用求余函数作为哈希函数
return key%MAX_LEN;
}
//搜索一个key值是否在对应桶中 存在则返回在桶中的索引值 不在则返回-1
int getPos(int key,int index){
for(int i = 0;i<set[index].size();i++){
if(set[index][i] == key){
//存在
return i;
}
}
//不存在
return -1;
}
public:
/** 初始化*/
MyHashSet() {
}
//添加元素
void add(int key) {
//所属哪个桶
int index = getIndex(key);
//该元素是否已经存在 存在则什么也不做
int pos = getPos(key,index);
if(pos<0){
//不存在 添加
set[index].push_back(key);
}
}
//删除元素
void remove(int key) {
int index = getIndex(key);
//是否存在 不存在什么也不做
int pos = getPos(key,index);
if(pos>=0){
//存在 删除指定位置的元素
set[index].erase(set[index].begin()+pos);
}
}
/** 某元素是否存在 */
bool contains(int key) {
//所属哪个桶
int index = getIndex(key);
//该元素是否存在
int pos = getPos(key,index);
if(pos>=0){
//存在
return true;
}else{
//不存在
return false;
}
}
};
设计哈希映射
题解:vector、list、pair实现
class MyHashMap {
private:
//list将元素按顺序存储在链表中
//pair是将两个数据组合成一组数据
vector<list<pair<int,int>>> data;
//定义一个常量 作为哈希求余函数的除数
static const int base = 769;
//哈希函数
static int hash(int key){
return key%base;
}
public:
/** 初始化*/
MyHashMap():data(base) {}
/** value will always be non-negative. */
void put(int key, int value) {
//得到哈希函数值
int h = hash(key);
//如果已经存在 更新value值然后返回
for(auto it = data[h].begin();it!=data[h].end();it++){
if((*it).first == key){
(*it).second = value;
return ;
}
}
//插入数据
data[h].push_back(make_pair(key,value));
}
/** 获取数据 不存在返回-1 */
int get(int key) {
int h = hash(key);
//从链表中搜索
for(auto it = data[h].begin();it!=data[h].end();it++){
if((*it).first == key){
return (*it).second;
}
}
//不存在
return -1;
}
/** 删除数据 */
void remove(int key) {
int h = hash(key);
//从链表中搜索
for(auto it = data[h].begin();it!=data[h].end();it++){
if((*it).first == key){
data[h].erase(it);
return ;
}
}
//不存在什么也不做
}
};