C++设计哈希映射 (七种解法)

解法1:暴力一维数组,适合于本身key值范围较小的情况。(面试官不会满足于这个解)

解法2:二维数组,稀疏数组节省空间。(略微比解法1好些,但是不如解法3,4)

解法3,4:chaining,链表法,对于hash到同一个key知道元素,用链表chaining起来,增加查找删除时要遍历每个key所对应的linkedList链表。(面试必会)

解法5,6双向链表实现的chaining。(解法5用STL的双向链表list, 解法6自我实现的双向链表)

解法7:开放定址法,线性探测

代码
解法1:暴力

class MyHashMap1 {
public:
    MyHashMap1() {
        const int N = 1000001;
        data = vector<int>(N, -1);
    }  
    void put(int key, int value) {
        data[key] = value;
    } 
    int get(int key) {
        if (data[key] != -1) {
            return data[key];
        }
        return -1;
    }    
    void remove(int key) {
        data[key] = -1;
    }
private:
    vector<int> data;
};

解法2:二维数组,稀疏数组节省空间

 class MyHashMap {
public:
    MyHashMap() {
        data.resize(N);
    }   
   auto getHashKey1(int key) {
        return key % N;
    }
    auto getHashKey2(int key) {
        return key / N;
    }
    void put(int key, int value) {
        auto hashKey1 = getHashKey1(key);
        auto hashKey2 = getHashKey2(key);
        if (data[hashKey1].empty()) {
            data[hashKey1].resize(N, -1);
        }
        data[hashKey1][hashKey2] = value;
    }
    int get(int key) {
        auto hashKey1 = getHashKey1(key);
        auto hashKey2 = getHashKey2(key);
        if (data[hashKey1].empty()) {
            return -1;
        }
        return data[hashKey1][hashKey2];
    }
    void remove(int key) {
        auto hashKey1 = getHashKey1(key);
        auto hashKey2 = getHashKey2(key);
        if (!data[hashKey1].empty()) {
            data[hashKey1][hashKey2] = -1;
        }
    }
private:
    const int N = 1001;
    vector<vector<int>> data;
};

解法3,4利用链表chaining最大化减少空间浪费。解法3,没有dummy head node,所有任何操作都要判断是否为空,代码会比较复杂,但是节省空间。解法4,每个链表预设一个dummy head,这样head永远不会为空,省去判断为空的情况,略费空间。

解法5,6利用STL的双端链表list和自己实现的双端链表。
解法3:

struct MyListNode {
    int key;
    int val;
    MyListNode* next;
    MyListNode() : key(-1), val(-1), next(nullptr) {}
    MyListNode(int _key, int _val) : key(_key), val(_val), next(nullptr) {}
};
class MyHashMap3 {
public:
    MyHashMap3() {
        nums.resize(N);
    }    
    void put(int key, int value) {
        auto hashKey = getHashKey(key);
        auto& head = nums[hashKey];
        if (head == nullptr) {
            head = new MyListNode(key, value);
            return;
        }
        auto p = head;
        auto tail = p;
        while (p != nullptr) {
            if (p->key == key) {
                p->val = value;
                return;
            }
            tail = p;
            p = p->next;
        }
        tail->next = new MyListNode(key, value); 
    }    
    int getHashKey(int key) {
        return key % N;
    }
    int get(int key) {
        auto hashKey = getHashKey(key);
        auto head = nums[hashKey];
        if (head == nullptr) {
            return -1;
        }
        auto p = head;
        while (p != nullptr) {
            if (p->key == key) {
               return p->val; 
            }
            p = p->next;
        }
        return -1;
    }  
    void remove(int key) {
        auto hashKey = getHashKey(key);
        // Note: if use auto head will cause crash,
        // we want to set head to nullptr if last element deleted
        auto& head = nums[hashKey];
        if (head == nullptr) {
            return; // not found
        }
        auto p = head;
        MyListNode* prev = nullptr;
        while (p != nullptr) {
            if (p->key == key) {
               if (prev == nullptr) {
                   auto dummy = head;
                   head = head->next;
                   dummy->next = nullptr;
                   delete dummy; // delete head;
               } else {
                   prev->next = p->next;
                   p->next = nullptr;
                   delete p;
               }
               return;
            }
            prev = p;
            p = p->next;
        }
    }
private:
    // The closest prime number around 1000 is 997 and 1009
    const static int N = 1009;
    vector<MyListNode*> nums;
};

解法4:

class MyHashMap {
public:
    MyHashMap() {
        nums.resize(N, new MyListNode());
    } 
    void put(int key, int value) {
        auto hashKey = getHashKey(key);
        auto& head = nums[hashKey];
        auto p = head;
        auto tail = p;
        while (p != nullptr) {
            if (p->key == key) {
                p->val = value;
                return;
            }
            tail = p;
            p = p->next;
        }
        tail->next = new MyListNode(key, value); 
    }    
    int getHashKey(int key) {
        return key % N;
    }

    int get(int key) {
        auto hashKey = getHashKey(key);
        auto& head = nums[hashKey];
        auto p = head;
        while (p != nullptr) {
            if (p->key == key) {
               return p->val; 
            }
            p = p->next;
        }

        return -1;
    } 
    void remove(int key) {
        auto hashKey = getHashKey(key);
        // Note: if use auto head will cause crash,
        // we want to set head to nullptr if last element deleted
        auto& head = nums[hashKey];
        MyListNode* prev = head;
        auto p = head->next;
        while (p != nullptr) {
            if (p->key == key) {
                prev->next = p->next;
                p->next = nullptr;
                delete p;
                return;
            }
            prev = p;
            p = p->next;
        }
    }
private:
    // The closest prime number around 1000 is 997 and 1009
    const static int N = 1009;
    vector<MyListNode*> nums;
};

解法5:

class MyHashMap {
public:
    /** Initialize your data structure here. */
    MyHashMap() {
        nums = vector<list<pair<int, int>>>(N);
    }
    
    int getHashKey(int key) {
        return key % N;
    }

    list<pair<int, int>>::iterator find(int key) {
        auto hashKey = getHashKey(key);
        auto& numList = nums[hashKey];
        for (auto iter = numList.begin(); iter != numList.end(); iter++) {
            if (iter->first == key) {
                return iter;
            }
        }

        return numList.end();
    }

    /** value will always be non-negative. */
    void put(int key, int value) {
        auto hashKey = getHashKey(key);
        auto iter = find(key);
        if (iter != nums[hashKey].end()) {
            iter->second = value;
            return;
        }

        nums[hashKey].push_back(make_pair(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) {
        auto hashKey = getHashKey(key);
        auto iter = find(key);
        if (iter != nums[hashKey].end()) {
            return iter->second;
        }

        return -1;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        auto hashKey = getHashKey(key);
        auto iter = find(key);
        if (iter != nums[hashKey].end()) {
            nums[hashKey].erase(iter);
        }
    }

private:
    static const int N = 1009;
    vector<list<pair<int, int>>> nums;
};

解法6,自己实现的双端链表,再不需要查找的前提下,比如给定node的iterator,双端链表可以O(1)删除,而单向链表不能。

struct MyListNode { // Doubly linked list node
    int key;
    int val;
    MyListNode* next;
    MyListNode* prev;
    
    MyListNode() : key(-1), val(-1), next(nullptr), prev(nullptr) {}
    MyListNode(int _key, int _val) : key(_key), val(_val), next(nullptr), prev(nullptr) {}
};

class MyHashMap {
public:
    /** Initialize your data structure here. */
    MyHashMap() {
        nums = vector<MyListNode*>(N, new MyListNode()); // create dummy node for each list
    }
    
    int getHashKey(int key) {
        return key % N;
    }

    MyListNode* find(int key) {
        auto hashKey = getHashKey(key);
        auto& head = nums[hashKey];
        auto p = head;
        while (p != nullptr) {
            if (p->key == key) {
                return p;
            }
            p = p->next;    
        }

        return nullptr;
    }

    /** value will always be non-negative. */
    void put(int key, int value) {
        auto hashKey = getHashKey(key);
        auto& head = nums[hashKey];
        auto p = find(key);
        if (p != nullptr) {
            p->val = value;
            return;
        }

        // Head insert it
        auto newNode = new MyListNode(key, value);
        newNode->next = head->next;
        if (head->next != nullptr) {
            head->next->prev = newNode;
        }
        head->next = newNode;
        newNode->prev = head;
    }
    
    int get(int key) {
        auto hashKey = getHashKey(key);
        auto& head = nums[hashKey];
        auto p = find(key);
        if (p != nullptr) {
            return p->val;
        }

        return -1;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        auto hashKey = getHashKey(key);
        auto& head = nums[hashKey];
        auto p = find(key);
        if (p != nullptr) {
            p->prev->next = p->next;
            if (p->next) {
                p->next->prev = p->prev;
            }
            delete p;
        }
    }

private:
    static const int N = 1009;
    vector<MyListNode*> nums;
};

解法7:开放定址法,线性探测

class MyHashMap {
public:
    MyHashMap() {
        hashTable = vector<pair<int, int>>(N, {-1, -1});
    }
    
    int find(int key) {
        int k = key % N;
        while (hashTable[k].first != key && hashTable[k].first != -1) {
            k = (k + 1) % N;
        }

        return k;
    }

    void put(int key, int value) {
        auto k = find(key);
        hashTable[k] = {key, value};
    }
    
    int get(int key) {
        auto k = find(key);
        if (hashTable[k].first == -1) {
            return -1;
        }

        return hashTable[k].second;
    } 
    
    void remove(int key) {
        auto k = find(key);
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值