「LeetCode算法精讲」设计哈希映射(Python)
off999 2024-10-04 19:00 22 浏览 0 评论
题目内容
不使用任何内建的哈希表库设计一个哈希映射
具体地说,你的设计应该包含以下的功能
- put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
- get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。
- remove(key):如果映射中存在这个键,删除这个数值对。
示例:
MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);
hashMap.put(2, 2);
hashMap.get(1); // 返回 1
hashMap.get(3); // 返回 -1 (未找到)
hashMap.put(2, 1); // 更新已有的值
hashMap.get(2); // 返回 1
hashMap.remove(2); // 删除键为2的数据
hashMap.get(2); // 返回 -1 (未找到)
注意:
- 所有的值都在 [0, 1000000]的范围内。
- 操作的总数目在[1, 10000]范围内。
- 不要使用内建的哈希库。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/design-hashmap
解法效率
LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。
解法一(使用链表作为存储空间)
【思路】
首先,我们使用取模运算作为哈希方法, 并选择较大的质数作为除数(KeyRange),以降低哈希碰撞的概率,在下例中我们使用1000以内最大的质数997;
然后,我们定义数组array作为存储空间,通过哈希方法计算键(key)的模,即在array数组中存储该键的下标。
接着,我们使用链表(Bucket)来存储模相同的数据。
具体实现如下:
class MyHashMap:
?
def __init__(self):
self.keyRange = 997
self.array = [Bucket() for _ in range(997)]
?
def _hash(self, key: int):
return key % self.keyRange
?
def put(self, key: int, value: int) -> None:
idx = self._hash(key)
self.array[idx].insert(key, value)
?
def get(self, key: int) -> int:
idx = self._hash(key)
return self.array[idx].get(key)
?
def remove(self, key: int) -> None:
idx = self._hash(key)
self.array[idx].remove(key)
?
?
class Node:
def __init__(self, key, val, next=None):
self.key = key
self.val = val
self.next = next
?
def gatherAttrs(self):
return ", ".join("{}: {}".format(k, getattr(self, k)) for k in self.__dict__.keys())
?
def __str__(self):
return self.__class__.__name__ + "{" + "{}".format(self.gatherAttrs()) + "}"
?
?
class Bucket:
?
def __init__(self):
self.root = Node(-1, None)
?
def insert(self, key, val):
node = self.root
last = self.root
while node:
if node.key == key:
node.val = val
break
last = node
node = node.next
else:
last.next = Node(key, val)
?
def get(self, key):
node = self.root
while node:
if node.key == key:
return node.val
node = node.next
return -1
?
def remove(self, key):
node = self.root
while node.next:
if node.next.key == key:
node.next = node.next.next
break
解法二(使用数组作为存储空间)
【思路】
我们改用数组作为存储空间,来存储模相同的数据。
具体实现如下:
class MyHashMap:
?
def __init__(self):
self.keyRange = 997
self.array = [Bucket() for _ in range(997)]
?
def _hash(self, key: int):
return key % self.keyRange
?
def put(self, key: int, value: int) -> None:
idx = self._hash(key)
self.array[idx].insert(key, value)
?
def get(self, key: int) -> int:
idx = self._hash(key)
return self.array[idx].get(key)
?
def remove(self, key: int) -> None:
idx = self._hash(key)
self.array[idx].remove(key)
?
?
class Bucket:
?
def __init__(self):
self.array = []
?
def insert(self, key, value):
for i, kv in enumerate(self.array):
if kv[0] == key:
self.array[i] = (key, value)
break
else:
self.array.append((key, value))
?
def get(self, key):
for (k, v) in self.array:
if k == key:
return v
else:
return -1
?
def remove(self, key):
for i, kv in enumerate(self.array):
if kv[0] == key:
del self.array[i]
相关推荐
- Python设计模式 第 13 章 中介者模式(Mediator Pattern)
-
在行为型模式中,中介者模式是解决“多对象间网状耦合”问题的核心模式。它就像“机场调度中心”——多个航班(对象)无需直接沟通起飞、降落时间,只需通过调度中心(中介者)协调,避免航班间的冲突与混乱...
- 1.3.1 python交互式模式的特点和用法
-
什么是Python交互模式Python交互模式,也叫Python交互式编程,是一种在Python解释器中运行的模式,它允许用户在解释器窗口中输入单个Python语句,并立即查看结果,而不需要编写整个程...
- Python设计模式 第 8 章 装饰器模式(Decorator Pattern)
-
在结构型模式中,装饰器模式是实现“动态功能扩展”的核心模式。它就像“手机壳与手机的关系”——手机(原始对象)具备通话、上网等基础功能,手机壳(装饰器)可在不改变手机本身的前提下,为其新增保护、...
- python设计模式 综合应用与实战指南
-
经过前面16章的学习,我们已系统掌握创建型模式(单例、工厂、建造者、原型)、结构型模式(适配器、桥接、组合、装饰器、外观、享元、代理)、行为型模式(责任链、命令、迭代器、中介者、观察者、状态、策略...
- Python入门学习教程:第 16 章 图形用户界面(GUI)编程
-
16.1什么是GUI编程?图形用户界面(GraphicalUserInterface,简称GUI)是指通过窗口、按钮、菜单、文本框等可视化元素与用户交互的界面。与命令行界面(CLI)相比,...
- Python 中 必须掌握的 20 个核心:str()
-
str()是Python中用于将对象转换为字符串表示的核心函数,它在字符串处理、输出格式化和对象序列化中扮演着关键角色。本文将全面解析str()函数的用法和特性。1.str()函数的基本用法1.1...
- Python偏函数实战:用functools.partial减少50%重复代码的技巧
-
你是不是经常遇到这样的场景:写代码时同一个函数调用了几十次,每次都要重复传递相同的参数?比如处理文件时总要用encoding='utf-8',调用API时固定传Content-Type...
- 第2节.变量和数据类型【第29课-输出总结】
-
同学们,关于输出的知识点讲解完成之后,把重点性的知识点做一个总结回顾。·首先对于输出这一章节讲解的比如有格式化符号,格式化符号这里需要同学们额外去多留意的是不是百分号s格式化输出字符串。当然课上也说百...
- AI最火语言python之json操作_python json.loads()
-
JSON(JavaScriptObjectNotation,JavaScript对象表示法)是一种开放标准的文件格式和数据交换格式,它易于人阅读和编写。JSON是一种常用的数据格式,比如对接各种第...
- python中必须掌握的20个核心函数—split()详解
-
split()是Python字符串对象的方法,用于将字符串按照指定的分隔符拆分成列表。它是文本处理中最常用的函数之一。一、split()的基本用法1.1基本语法str.split(sep=None,...
- 实用方法分享:pdf文件分割方法 横向A3分割成纵向A4
-
今天在街上打印店给儿子打印试卷时,我在想:能不能,把它分割成A4在家中打印,这样就不需要跑到街上的打印店打印卷子了。原来,老师发的作业,是电子稿,pdf文件,A3格式的试卷。可是家中的打印机只能打印A...
- 20道常考Python面试题大总结_20道常考python面试题大总结免费
-
20道常考Python面试题大总结关于Python的面试经验一般来说,面试官会根据求职者在简历中填写的技术及相关细节来出面试题。一位拿了大厂技术岗SpecialOffer的网友分享了他总结的面试经...
- Kotlin Data Classes 快速上手_kotlin快速入门
-
引言在日常开发中,我们常常需要创建一些只用来保存数据的类。问题是,这样的类往往需要写一堆模板化的方法:equals()、hashCode()、toString()……每次都重复,既枯燥又容易出错。//...
- python自动化RobotFramework中Collections字典关键字使用(五)
-
前言介绍安装好robotframework库后,跟之前文章介绍的BuiltIn库一样BuiltIn库使用介绍,在“python安装目录\Lib\site-packages\robot\librarie...
- Python中numpy数据分析库知识点总结
-
Python中numpy数据分析库知识点总结二、对已读取数据的处理②指定一个值,并对该值双边进行修改③指定两个值,并对第一个值的左侧和第二个值的右侧进行修改2.4数组的拼接和行列交换①竖直拼接(np...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- Python设计模式 第 13 章 中介者模式(Mediator Pattern)
- 1.3.1 python交互式模式的特点和用法
- Python设计模式 第 8 章 装饰器模式(Decorator Pattern)
- python设计模式 综合应用与实战指南
- Python入门学习教程:第 16 章 图形用户界面(GUI)编程
- Python 中 必须掌握的 20 个核心:str()
- Python偏函数实战:用functools.partial减少50%重复代码的技巧
- 第2节.变量和数据类型【第29课-输出总结】
- AI最火语言python之json操作_python json.loads()
- python中必须掌握的20个核心函数—split()详解
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)