[LeetCode] Design HashMap 设计HashMap

时间:2022-01-30 09:45:07

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. &lbrack;LeetCode&rsqb; Design HashSet 设计HashSet

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

  2. &lbrack;LeetCode&rsqb; Design Twitter 设计推特

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

  3. &lbrack;LeetCode&rsqb; 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. &lbrack;LeetCode&rsqb; 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. &lbrack;Java&rsqb; 遍历HashMap和HashMap转换成List的两种方式

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

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

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

  8. &equals;&equals; 和 equals,equals 与 hashcode,HashSet 和 HashMap,HashMap 和 Hashtable

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

  9. LeetCode初级算法--设计问题01:Shuffle an Array (打乱数组)

    LeetCode初级算法--设计问题01:Shuffle an Array (打乱数组) 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:h ...

随机推荐

  1. Web服务器与数据库服务器分离 导入 Excel数据至数据库

    一般情况一般项目WEB服务器与数据库均部署在一台服务器,文件上传,数据导入在一台服务器完成.web服务器与数据库服务器分离,文件上传与数据导入将分布在两台服务器或多台服务器之间.本案例为两台服务器,具 ...

  2. Android笔记——Android五大布局

    一.五大布局 Android的界面是有布局和组件协同完成的,布局好比是建筑里的框架,而组件则相当于建筑里的砖瓦.组件按照布局的要求依次排列,就组成了用户所看见的界面.Android的五大布局分别是Li ...

  3. w530 在ubuntu 12&period;04 &lowbar;x64 背光调节方法

    So to get the screen brightness keys working with your Nvidia graphics card, create a file in the xo ...

  4. zendstudio -chinese

    http://archive.eclipse.org/technology/babel/index.php http://www.eclipse.org/babel/downloads.php 注册码 ...

  5. 【js编程艺术】小制作五

    1.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <ti ...

  6. 【笔记】归纳js getcomputedStyle&comma; currentStyle 以及其相关用法

      好吧,鉴于前端则个行业知识宽度广而深,早期看过高程介绍过的获取元素计算后的最终样式(浏览器显示的最终样式)的方法现在也忘得七七八八了 于是百度了一下,看了一下大神张鑫旭的博客,这里写个随笔记录一下 ...

  7. firefox修改语言

    下面咱们就可以开始更改设置来让咱们安装好的语言成为默认的语言. 首先在空窗口里输入以下地址:about:config,进入设置页面. 2 请大家定位到general.useragent.locale这 ...

  8. 《Linux内核设计与实现》第一二章笔记

    第一章 linux内核简介 每个处理器在任何时间点上的活动必然概括为下列三者: 运行于用户空间,执行用户进程 运行于内核空间,处于进程上下文,代表某个特定的进程执行 运行于内核空间,处于中断上下文,与 ...

  9. 【Ray Tracing The Next Week 超详解】 光线追踪2-9

    我们来整理一下项目的代码 目录 ----include --hit --texture --material ----RTdef.hpp ----ray.hpp ----camera.hpp ---- ...

  10. thinkphp查询缓存

    S()函数的使用:  ThinkPHP把各种缓存方式都抽象成统一的缓存类来调用,而且ThinkPHP把所有的缓存机制统一成一个S方法来进行操作,所以在使用  不同的缓存方式的时候并不需要关注具体的缓存 ...