Colección de hash de diseño LeetCode705.

705. Colección Design Hash

Dificultad: 简单
Descripción del título:

Diseñe un conjunto hash (HashSet) sin utilizar ninguna biblioteca de tablas hash incorporada. Implementar la clase MyHashSet:
void add (key) inserta la clave de valor en el conjunto de hash.
bool contiene (clave) Devuelve si esta clave de valor existe en el conjunto hash.
void remove (key) Elimina la clave de valor dada del conjunto de hash. Si no existe tal valor en el conjunto de hash, no se hace nada.

Ejemplo:

输入:
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
输出:
[null, null, null, true, false, null, true, null, false]

Explicación:

MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1);      // set = [1]
myHashSet.add(2);      // set = [1, 2]
myHashSet.contains(1); // 返回 True
myHashSet.contains(3); // 返回 False ,(未找到)
myHashSet.add(2);      // set = [1, 2]
myHashSet.contains(2); // 返回 True
myHashSet.remove(2);   // set = [1]
myHashSet.contains(2); // 返回 False ,(已移除)

inmediato:

0 <= Clave <= 10. 6
llamadas hasta 10. 4 veces agregan, eliminan y contienen.

class MyHashSet {
    
    
public:
    /** Initialize your data structure here. */
    map<int,int> mp;
    MyHashSet() {
    
    
        
    }
    int i=1;
    void add(int key) {
    
    
        if(mp[key]==0){
    
    
            mp[key]=i;
            i++;
        }
    }
    
    void remove(int key) {
    
    
        if(mp[key]!=0){
    
    
            mp[key]=0;
        }
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
    
    
        return mp[key]!=0;
    }
};

/**
 * 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);
 */

O usa una matriz directamente

class MyHashSet {
    
    
public:
    /** Initialize your data structure here. */
    int mp[1000001];
    MyHashSet() {
    
    
        memset(mp,0,sizeof(mp));
    }
    void add(int key) {
    
    
        if(mp[key]==0){
    
    
            mp[key]=1;
        }
    }
    
    void remove(int key) {
    
    
        if(mp[key]==1){
    
    
            mp[key]=0;
        }
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
    
    
        return mp[key]==1;
    }
};

/**
 * 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);
 */

Supongo que te gusta

Origin blog.csdn.net/chaokudeztt/article/details/114745188
Recomendado
Clasificación