[LeetCode] Design HashMap 设计HashMap
Design a HashMap without using any built-in hash table libraries.
To be specific, your design should include these functions:
put(key, value)
: Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.get(key)
: Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.remove(key)
: Remove the mapping for the value key if this map contains the mapping for the key.
Example:
- MyHashMap hashMap = new MyHashMap();
- hashMap.put(1, 1);
- hashMap.put(2, 2);
- hashMap.get(1); // returns 1
- hashMap.get(3); // returns -1 (not found)
- hashMap.put(2, 1); // update the existing value
- hashMap.get(2); // returns 1
- hashMap.remove(2); // remove the mapping for 2
- hashMap.get(2); // returns -1 (not found)
Note:
- All keys and values will be in the range of
[0, 1000000]
. - The number of operations will be in the range of
[1, 10000]
. - Please do not use the built-in HashMap library.
这道题让我们设计一个HashMap的数据结构,不能使用自带的哈希表,跟之前那道 Design HashSet 很类似,之前那道的两种解法在这里也是行得通的,既然题目中说了数字的范围不会超过 1000000,那么就申请这么大空间的数组,只需将数组的初始化值改为 -1 即可。空间足够大了,就可以直接建立映射,移除时就将映射值重置为 -1,由于默认值是 -1,所以获取映射值就可以直接去,参见代码如下:
解法一:
- class MyHashMap {
- public:
- MyHashMap() {
- data.resize(, -);
- }
- void put(int key, int value) {
- data[key] = value;
- }
- int get(int key) {
- return data[key];
- }
- void remove(int key) {
- data[key] = -;
- }
- private:
- vector<int> data;
- };
我们可以来适度的优化一下空间复杂度,由于存入 HashMap 的映射对儿也许不会跨度很大,那么直接就申请长度为 1000000 的数组可能会有些浪费,其实可以使用 1000 个长度为 1000 的数组来代替,那么就要用个二维数组啦,实际上开始只申请了 1000 个空数组,对于每个要处理的元素,首先对 1000 取余,得到的值就当作哈希值,对应申请的那 1000 个空数组的位置,在建立映射时,一旦计算出了哈希值,将对应的空数组 resize 为长度 1000,然后根据哈希值和 key/1000 来确定具体的加入映射值的位置。获取映射值时,计算出哈希值,若对应的数组不为空,直接返回对应的位置上的值。移除映射值一样的,先计算出哈希值,如果对应的数组不为空的话,找到对应的位置并重置为 -1。参见代码如下:
解法二:
- class MyHashMap {
- public:
- MyHashMap() {
- data.resize(, vector<int>());
- }
- void put(int key, int value) {
- int hashKey = key % ;
- if (data[hashKey].empty()) {
- data[hashKey].resize(, -);
- }
- data[hashKey][key / ] = value;
- }
- int get(int key) {
- int hashKey = key % ;
- if (!data[hashKey].empty()) {
- return data[hashKey][key / ];
- }
- return -;
- }
- void remove(int key) {
- int hashKey = key % ;
- if (!data[hashKey].empty()) {
- data[hashKey][key / ] = -;
- }
- }
- private:
- vector<vector<int>> data;
- };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/706
类似题目:
参考资料:
https://leetcode.com/problems/design-hashmap
https://leetcode.com/problems/design-hashmap/discuss/152746/Java-Solution
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Design HashMap 设计HashMap的更多相关文章
- [LeetCode] Design HashSet 设计HashSet
Design a HashSet without using any built-in hash table libraries. To be specific, your design should ...
- [LeetCode] Design Twitter 设计推特
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and ...
- [LeetCode] Design Tic-Tac-Toe 设计井字棋游戏
Design a Tic-tac-toe game that is played between two players on a n x n grid. You may assume the fol ...
- [LeetCode] Design TinyURL 设计精简URL地址
Note: For the coding companion problem, please see: Encode and Decode TinyURL. How would you design ...
- LeetCode 622:设计循环队列 Design Circular Queue
LeetCode 622:设计循环队列 Design Circular Queue 首先来看看队列这种数据结构: 队列:先入先出的数据结构 在 FIFO 数据结构中,将首先处理添加到队列中的第一个元素 ...
- HashMap设计原理与实现(下篇)200行带你写自己的HashMap!!!
HashMap设计原理与实现(下篇)200行带你写自己的HashMap!!! 我们在上篇文章哈希表的设计原理当中已经大体说明了哈希表的实现原理,在这篇文章当中我们将自己动手实现我们自己的HashMap ...
- [Java] 遍历HashMap和HashMap转换成List的两种方式
遍历HashMap和HashMap转换成List /** * convert the map to the list(1) */ public static void main(String[] ...
- Java基础知识强化之集合框架笔记62:Map集合之HashMap嵌套HashMap
1. HashMap嵌套HashMap 传智播客 jc 基础班 陈玉楼 20 高跃 ...
- == 和 equals,equals 与 hashcode,HashSet 和 HashMap,HashMap 和 Hashtable
一:== 和 equals == 比较引用的地址equals 比较引用的内容 (Object 类本身除外) String obj1 = new String("xyz"); Str ...
随机推荐
- NSE: known a priori estimate
1. Leray-Hopf $u\in L^\infty(0,T;L^2(\bbR^3))\cap L^2(0,T;H^1(\bbR^3))$. See [Leray, Jean. Sur le mo ...
- Geometric regularity criterion for NSE: the cross product of velocity and vorticity 2: $u\times \om\cdot \n\times \om$
在 [Lee, Jihoon. Notes on the geometric regularity criterion of 3D Navier-Stokes system. J. Math. Phy ...
- python,可变对象,不可变对象,深拷贝,浅拷贝。
学习整理,若有问题,欢迎指正. python 可变对象,不可变对象 可变对象 该对象所指定的内存地址上面的值可以被改变,变量被改变后,其所指向的内存地址上面的值,直接被改变,没有发生复制行为,也没有发 ...
- CemtOS7更改yum网易 阿里云的yum源。
一,鉴于用国外的Yum源,速度比较慢,所以想到将国外的yum源,改为国内的Yum源,著名的有网易 阿里云源.如何更改呢? 二,更改yum源为网易的. 首先备份/etc/yum.repos.d/Cent ...
- 使用PHP做分页查询(查询结果也显示为分页)
1.先把数据库里所有的数据分页显示在页面,并在显示数据的表格上方加上查询表单.(加上条件,实现目标结果.) <!DOCTYPE html PUBLIC "-//W3C//DTD XHT ...
- 共通脚本utils
/** * 模块名:共通脚本 * 程序名: 通用工具函数 **/ var utils = {}; /** * 格式化字符串 * 用法: .formatString("{0}-{1}" ...
- frame的用法
<iframe> 标签规定一个内联框架.一个内联框架被用来在当前 HTML 文档中嵌入另一个文档. 所有的主流浏览器都支持<iframe>标签.你可以把提示的文字放到 < ...
- djang增删改查
创建表: from django.db import models class Publisher(models.Model): pid = models.AutoField(primary_key ...
- 51nod 1423 最大二“货” 单调栈
利用单调栈,高效求出每个区间内的最大值和次大值的亦或值. 先正向扫描,利用单调递减栈,若当前栈为空栈,则直接压入栈中,若为非空栈,弹出栈顶元素,每弹出一个元素,则求一次亦或值,保留最大值 接着进行反向 ...
- 【转载】Pytorch tutorial 之Datar Loading and Processing
前言 上文介绍了数据读取.数据转换.批量处理等等.了解到在PyTorch中,数据加载主要有两种方式: 1.自定义的数据集对象.数据集对象被抽象为Dataset类,实现自定义的数据集需要继承Datase ...