【LeetCode】 705. 706. 设计哈希映射\集合

本文介绍了如何在不使用内置哈希表的情况下设计哈希集合和哈希映射。对于705题,通过创建一个布尔型向量并为每个添加的元素设置为true来实现添加和查找功能。而对于706题,采用整型向量,初始化值为-1,实现插入、获取和删除键值对的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.题目

705:

不使用任何内建的哈希表库设计一个哈希集合
具体地说,你的设计应该包含以下的功能
add(value):向哈希集合中插入一个值。
contains(value) :返回哈希集合中是否存在这个值。
remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。

706:

不使用任何内建的哈希表库设计一个哈希映射 具体地说,你的设计应该包含以下的功能 put(key,
value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。 remove(key):如果映射中存在这个键,删除这个数值对。

2.思路

705:
建立布尔类型向量,初始值均为false;
add:每加入一个数,对应值改为true;
706:
建立int类型向量,初始化值均为-1;
put:把对应数字改变

3.代码

class MyHashSet {
public:
    /** Initialize your data structure here. */
    MyHashSet() {
        hashSet = vector<bool> (1000001, false);
    }
    
    void add(int key) {
        hashSet[key] = true;
        return ;
    }
    
    void remove(int key) {
        if(hashSet[key]) {
            hashSet[key] = false;
            return ;
        }
        return ;
    }
    
    /** Returns true if this set did not already contain the specified element */
    bool contains(int key) {
        return hashSet[key];
    }
    private:
        vector<bool> hashSet;
};
class MyHashMap {
public:
    /** Initialize your data structure here. */
    MyHashMap() {
        HashMap = vector<int> (1000001, -1);
    }
    
    /** value will always be positive. */
    void put(int key, int value) {
        HashMap[key] = value;
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
        return HashMap[key];
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        HashMap[key] = -1;
    }
    private:
        vector<int> HashMap;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值