数据结构笔记--哈希表的相关应用(RandomPool结构,布隆过滤器和一致性哈希算法)

目录

1--RandomPool结构

2--布隆过滤器

3--一致性哈希


1--RandomPool结构

设计一种 RandomPool 结构,要求具有以下三种功能:

        ① insert(key):将某个 key 加入到结构中,并做到不重复加入;

        ② delete(key):移除结构中的key;

        ③ getRandom():等概率随机返回结构中的一个key;

要求:以上三种功能的时间复杂度都是 O(1);

主要思路:

        使用两个哈希表 indexKeymap 和 keyIndexmap 来存储(key, index) 和 (index, key),其中index从0开始连续增长,与哈希表的大小有关;

#include <iostream>
#include <unordered_map>
#include <string>

class randomPool{
public:
    void insertKey(std::string key){
        if(keyIndexmap.find(key) == keyIndexmap.end()){
            keyIndexmap[key] = this->size;
            indexKeymap[this->size] = key;
            this->size++;
        }
    }

    void deleteKey(std::string key){
        if(keyIndexmap.find(key) != keyIndexmap.end()){
            int deleteIndex = keyIndexmap[key];
            int lastIndex = this->size - 1;
            std::string lastKey = indexKeymap[lastIndex];
            // 使用(lastKey, lastIndex)替换删除的(key, deleteIndex)
            keyIndexmap[lastKey] = deleteIndex;
            indexKeymap[deleteIndex] = lastKey;
            // 移除(key, deleteIndex) 和 (lastIndex, lastKey)
            // 此步骤的意义是确保indexKeymap中的index是逻辑连续的,以便getRandomKey()的调用
            keyIndexmap.erase(key);
            indexKeymap.erase(lastIndex);
        }
    }

    std::string getRandomKey(){
        //随机生成[0, size - 1]上的 index
        int random = rand() % size;
        return indexKeymap[random];
    }

public:
    std::unordered_map<std::string, int> keyIndexmap;
    std::unordered_map<int, std::string> indexKeymap;
    int size = 0;
};

int main(int argc, char *argv[]){
    randomPool rp1;
    rp1.insertKey("A");
    rp1.insertKey("B");
    rp1.insertKey("C");
    std::cout << "***************keyIndexmap: " << std::endl;
    for(auto &it : rp1.keyIndexmap){
        std::cout << "(" << it.first << ", " << it.second << ")" << std::endl; 
    }

    std::cout << "***************indexKeymap: " << std::endl;
    for(auto &it : rp1.indexKeymap){
        std::cout << "(" << it.first << ", " << it.second << ")" << std::endl; 
    }

    std::cout << "***************After deleteKey:" << std::endl;
    rp1.deleteKey("A");
    std::cout << "***************keyIndexmap: " << std::endl;
    for(auto &it : rp1.keyIndexmap){
        std::cout << "(" << it.first << ", " << it.second << ")" << std::endl; 
    }

    std::cout << "***************getRandomkey: " << rp1.getRandomKey() << std::endl;
    return 0;
}

2--布隆过滤器

布隆过滤器一般用于信息检索,视频讲解可以参考:布隆过滤器讲解(视频1:08:00开始)

3--一致性哈希

一致性哈希算法常用于负载均衡上,视频讲解可以参考:7分钟视频详解一致性hash算法

猜你喜欢

转载自blog.csdn.net/weixin_43863869/article/details/132367688