数据结构之哈希

 

题目1:实现一个简单的哈希结构 https://leetcode-cn.com/problems/design-hashmap/

使用YouLookDeliciousC的做法,即用拉链表来实现。

技巧是vector<Node*>来做为容器

struct Node {
    int key;
    int val;
    Node* next;
    Node(int _key,int _val):key(_key),val(_val),next(nullptr){}
};

int len = 1000;
class MyHashMap {
public:
    //哈希表的顶底层结构
    //1.哈希函数的设计
    //2.哈希冲突的方法
    //3.动态扩容的策略
    vector<Node*> arr;

    MyHashMap() {
        arr = vector<Node*>(len, new Node(-1, -1));
    }

    void put(int key, int value) {
        int bucket = key % len;
        Node* cur = arr[bucket];//获取当前的桶
        Node* pre = nullptr;
        while (cur) {
            //如果存在这个值
            if (cur->key == key) {
                cur->val = value;
                return;
            }
            pre = cur;
            cur = cur->next;
        }
        pre->next = new Node(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) {
        int bucket = key % len;
        Node* cur = arr[bucket];
        while (cur) {
            if (cur->key == key) {
                return cur->val;
            }
            cur = cur->next;
        }
        return -1;
    }

    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        int bucket = key % len;
        Node* cur = arr[bucket];
        Node* pre = nullptr;
        while (cur) {
            if (cur->key == key) {
                pre->next = cur->next;
                return;
            }
            pre = cur;
            cur = cur->next;
        }
    }
};

 

关于哈希还有什么可以说的呢?

1.设计哈希函数(要求) 

常用的哈希函数总结:

https://leetcode-cn.com/explore/learn/card/hash-table/206/practical-application-design-the-key/824/

2.防止冲突的方法:

开放寻址法

拉链法

3.装载因子

对于开放寻址法:装入的数量/数组的空间

对于拉链法:m/n

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值