HashMap的实现

正好最近在用python尝试构建hash表,顺道把这道题也一起解了。 
用Python实现的一个简单的Hash表,采用hash函数是取余,用线性探测解决冲突问题。

class HashTable:

    # 初始化
    def __init__(self, size):
        self.elem = [None for i in range(size)]                # 创建一个列表保存哈希元素,值全为None
        self.count = size                                      # 最大表长

    # 散列函数
    def hash(self, key):
        return key % self.count                                # 散列函数采用除留余数法

    # 插入
    def insert_hash(self, key):
        print(key)
        address = self.hash(key)                               # 计算散列地址
        print(address)
        while self.elem[address] != None:                      # 发生冲突
            address = (address + 1) % self.count               # 线性探测解决冲突
        print(address)
        self.elem[address] = key                               # 没有冲突
        print(self.elem)

    # 查找
    def search_hash(self, key):
        star = address = self.hash(key)                               # 查找关键字
        while self.elem[address] != key:
            address = (address + 1) % self.count
            if not self.elem[address] or address == star:             # 说明没找到或者循环到了开始的位置
                return False
        return True

if __name__ == '__main__':
    list_a = [0, 12, 67, 56, 16, 25, 37, 22, 29, 15, 47, 48, 34]
    hash_table = HashTable(len(list_a))
    for i in list_a:
        hash_table.insert_hash(i)

    for i in hash_table.elem:
        if i:
            print((i, hash_table.elem.index(i)))

    print(hash_table.search_hash(15))
    print(hash_table.search_hash(33))

针对这道题,也可以采用取余作为hash函数,采用“拉链法”处理冲突,将相同hash值的对象组织成一个链表放在hash值对应的位置;具体原理和Java中的HashMap实现的原理类似。具体代码如下:

class MyHashMap:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.buckets = 1000                       # 键值块,哈希桶
        self.itemsPerBuckect = 1001               # 产生冲突的“拉链”块
        self.hashmap = [[] for _ in range(self.buckets)]        # _表示临时变量,仅用一次,后面无需用到

    # 散列函数
    def hash(self, key):
        return key % self.buckets                 # 取余

    # 处理冲突的函数
    def pos(self, key):
        return key // self.buckets                # 向下取整,返回商的整数部分

    def put(self, key, value):
        """
         value will always be positive.
         :type key: int
         :type value: int
         :rtype: void
        """
        hashkey = self.hash(key)
        if not self.hashmap[hashkey]:                 # 没有产生冲突,直接填入buckets中
            self.hashmap[hashkey] = [None] * self.itemsPerBuckect
        self.hashmap[hashkey][self.pos(key)] = value

    def get(self, key):
        """
        Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
        :type key: int
        :rtype: int
        """
        hashkey = self.hash(key)
        if(not self.hashmap[hashkey]) or self.hashmap[hashkey][self.pos(key)] == None:      # 没有找到这个值
            return -1
        else:
            return self.hashmap[hashkey][self.pos(key)]

    def remove(self, key):
        """
        Removes the mapping of the specified value key if this map contains a mapping for the key
        :type key: int
        :rtype: void
        """
        hashkey = self.hash(key)
        if self.hashmap[hashkey]:
            self.hashmap[hashkey][self.pos(key)] = None


if __name__ == "__main__":
    hashmap = MyHashMap()
    hashmap.put(1, 1)
    hashmap.put(2, 2)
    hashmap.get(1)
    hashmap.get(3)
    hashmap.put(2, 1)
    hashmap.get(2)
    hashmap.remove(2)
    hashmap.get(2)

python极简版本:

class MyHashMap:

    def __init__(self):
        self.arr = [-1] * 1000001

    def put(self, key, value):
        self.arr[key] = value

    def get(self, key):
        return self.arr[key]

    def remove(self, key):
        self.arr[key] = -1

c++实现版本,直接用vector容器模拟,没有考虑冲突情况。

class MyHashMap {
public:
    /** Initialize your data structure here. */
    vector<int> hashMap;
    MyHashMap() {

    }

    /** value will always be non-negative. */
    void put(int key, int value) {
        if(key >= hashMap.size()){
            for(int i = hashMap.size(); i <= key; i++){
                hashMap.push_back(-1);
            }
        }
        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) {
        if(key >= hashMap.size()) 
            return -1;
        return hashMap[key];

    }

    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        if(key >= hashMap.size()) 
            return;
        hashMap[key] = -1;
    }
};

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值