20多行代码设计简单双值存储哈希set结构

题目:Design a HashSet without using any built-in hash table libraries.

Implement MyHashSet class:

void add(key) Inserts the value key into the HashSet. bool
contains(key) Returns whether the value key exists in the HashSet or
not. void remove(key) Removes the value key in the HashSet. If key
does not exist in the HashSet, do nothing.
在这里插入图片描述

class MyHashSet {
private:
	//哈希散列和成员变量
    vector<list<int>> vec;
    static const int base = 888;
    static int hash(int k){
        return k % base;
    }
public:
	//init初始化
    MyHashSet():vec(base) {}
    
    //散列哈希,对哈希数组散列元素的列表集合添加无重复元素key
    void add(int key) {
        int a = hash(key);
        //枚举数组i存储的列表
        for(auto it = vec[a].begin();it != vec[a].end();it++){
        	//相同元素返回
            if((*it) == key){return;}
        }
        vec[a].push_back(key);
    }
    
    //散列哈希,对哈希数组散列元素的列表集合删除无重复元素key
    void remove(int key) {
        int a = hash(key);
        //枚举数组i存储的列表
        for(auto it = vec[a].begin();it != vec[a].end();it++){
        	//遇到key相同元素,删除
            if((*it) == key){
                vec[a].erase(it);
                return;
            }
        }
    }
    
    //散列哈希,对哈希数组散列元素的列表集合是否包含无重复元素key
    bool contains(int key) {
        int a = hash(key);
        //枚举数组i存储的列表
        for(auto it = vec[a].begin();it != vec[a].end();it++){
        	//找到key,返回真
            if((*it) == key){
                return true;
            }
        }
        return false;
    }
};

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet* obj = new MyHashSet();
 * obj->add(key);
 * obj->remove(key);
 * bool param_3 = obj->contains(key);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值