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

类似题目:

Design HashSet

参考资料:

https://leetcode.com/problems/design-hashmap

https://leetcode.com/problems/design-hashmap/discuss/152746/Java-Solution

https://leetcode.com/problems/design-hashmap/discuss/184764/Easy-C%2B%2B-Solution-beats-98.01(52-msec)-using-array-of-vectors

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Design HashMap 设计HashMap的更多相关文章

  1. [LeetCode] Design HashSet 设计HashSet

    Design a HashSet without using any built-in hash table libraries. To be specific, your design should ...

  2. [LeetCode] Design Twitter 设计推特

    Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and ...

  3. [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 ...

  4. [LeetCode] Design TinyURL 设计精简URL地址

    Note: For the coding companion problem, please see: Encode and Decode TinyURL. How would you design ...

  5. LeetCode 622:设计循环队列 Design Circular Queue

    LeetCode 622:设计循环队列 Design Circular Queue 首先来看看队列这种数据结构: 队列:先入先出的数据结构 在 FIFO 数据结构中,将首先处理添加到队列中的第一个元素 ...

  6. HashMap设计原理与实现(下篇)200行带你写自己的HashMap!!!

    HashMap设计原理与实现(下篇)200行带你写自己的HashMap!!! 我们在上篇文章哈希表的设计原理当中已经大体说明了哈希表的实现原理,在这篇文章当中我们将自己动手实现我们自己的HashMap ...

  7. [Java] 遍历HashMap和HashMap转换成List的两种方式

    遍历HashMap和HashMap转换成List   /** * convert the map to the list(1) */ public static void main(String[] ...

  8. Java基础知识强化之集合框架笔记62:Map集合之HashMap嵌套HashMap

    1. HashMap嵌套HashMap  传智播客          jc    基础班                      陈玉楼  20                      高跃   ...

  9. == 和 equals,equals 与 hashcode,HashSet 和 HashMap,HashMap 和 Hashtable

    一:== 和 equals == 比较引用的地址equals 比较引用的内容 (Object 类本身除外) String obj1 = new String("xyz"); Str ...

随机推荐

  1. Spark SQL相关总结

    1.spark 数据透视图: pivot(pivot_col, values=None) Pivots a column of the current [[DataFrame]] and perfor ...

  2. NightWatch端到端测试

    NightWatch http://nightwatchjs.org/ Nightwatch.js Browser automated testing done easy. Write End-to- ...

  3. MySQL的一些基本命令笔记(4)

    delete 语句嵌套子查询: delete from 表名1 where 列名 操作符 (select 列名 from 表名2 where 条件); 示例: delete from customer ...

  4. python数据结构之堆(heap)

    本篇学习内容为堆的性质.python实现插入与删除操作.堆复杂度表.python内置方法生成堆. 区分堆(heap)与栈(stack):堆与二叉树有关,像一堆金字塔型泥沙:而栈像一个直立垃圾桶,一列下 ...

  5. 如何使用AB PLC仿真软件Studio 5000 Logix Emulate

    前言:在学习PLC编程或程序开发过程中,如果身边没有实体PLC,又想验证程序逻辑,这时,仿真软件是不错的选择.针对AB PLC的仿真软件Studio 5000 Logix Emulate,有的同学说: ...

  6. Stm32复习之时钟系统

    地点:南图 这部分的内容是整个STM32学习知识的核心,不管是什么微控制器处理器,时钟系统都是其核心类似于人之心脏,因此学好理解这一章节至关重要. 为了便于理解这一系统,将从以下几个层次来讲.(忘了是 ...

  7. GPS车辆监控系统的启动方式

    我们通常用到的GPS车辆监控系统都有哪些启动方式,又有什么区别呢?通常GPS车辆监控系统都有热启.冷启.温启的技术指标,现参考如下:GPS开机定位分为冷启动.温启动和热启动三种:一.冷启动:以下几种情 ...

  8. kafka知识点详解

    第一部分:kafka概述 一.定义(消息引擎系统) 一句话概括kafka的核心功能就是:高性能的消息发送与高性能的消息消费. kafka刚推出的时候是以消息引擎的身份出现的,它具有强大的消息传输效率和 ...

  9. Laravel 多数据库配置及查询操作

    laravel文档好像没有写得很详细 https://docs.golaravel.com/docs/5.3/database/ Using Multiple Database Connections ...

  10. Laravel -- 邮箱功能配置问题

    ```` 今天碰到了这块的问题,还是记一下 ```` 关于邮箱: 品牌:腾讯qq.网易163 等 种类:个人.企业 邮箱服务器种类 配置教程 https://jingyan.baidu.com/art ...