这是悦乐书的第299次更新,第318篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第167题(顺位题号是706)。在不使用任何内置哈希表库的情况下设计HashMap。具体而言,你的设计应包括以下功能:

put(key,value):将一个(key,value)对插入HashMap。如果该值已存在于HashMap中,请更新该值。

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(未找到)



注意

  • 所有key和value都将在[0,1000000]范围内。

  • 操作次数将在[1,10000]范围内。

  • 请不要使用内置的HashMap库。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

为了实现键值对的效果,内层使用了二维数组,外层使用ArrayList。其中二维数组是一个一行两列的结构,第一行第一列存储key的值,第一行第二列存储value的值。另外,我们还需要单独写一个contains方法,来判断当前的key是否存在于HashMap中。

put方法的时间复杂度为O(n),get方法的时间复杂度为O(n),remove的时间复杂度为O(n),contains方法的时间复杂度为O(n)。

class MyHashMap {

    List<int[][]> list;
/** Initialize your data structure here. */
public MyHashMap() {
list = new ArrayList<int[][]>();
} /** value will always be non-negative. */
public void put(int key, int value) {
if (contains(key)) {
for (int[][] arr : list) {
if (arr != null && arr[0][0] == key) {
arr[0][1] = value;
break;
}
}
} else {
list.add(new int[][]{{key, value}});
}
} public boolean contains(int key){
for (int[][] arr : list) {
if (arr != null && arr[0][0] == key) {
return true;
}
}
return false;
} /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
for (int[][] arr : list) {
if (arr != null && arr[0][0] == key) {
return arr[0][1];
}
}
return -1;
} /** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
if (contains(key)) {
for (int i=0; i<list.size(); i++) {
if (list.get(i)[0][0] == key) {
list.remove(i);
break;
}
}
}
}
} /**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/

03 第二种解法

我们也可以使用一个小track,依旧使用数组,但是变成了一维数组,因为题目给定了key和value的范围,所以数组的容量为其最大范围加1。因为最小值可以为0,而数组默认值是0,避免误判,将数组的初始值全部赋值为-1。

put方法的时间复杂度为O(1),get方法的时间复杂度为O(1),remove的时间复杂度为O(1),但是空间复杂度较高。

class MyHashMap {

    int[] arr;
/** Initialize your data structure here. */
public MyHashMap() {
arr = new int[1000001];
Arrays.fill(arr, -1);
} /** value will always be non-negative. */
public void put(int key, int value) {
arr[key] = value;
} /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
return arr[key];
} /** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
arr[key] = -1;
}
} /**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/

04 第三种解法

使用单链表,此解法是参考至讨论区。传送门:https://leetcode.com/problems/design-hashmap/discuss/227081/Java-Solutions

class MyHashMap {

    /** Initialize your data structure here. */
ListNode[] nodes;
public MyHashMap() {
nodes = new ListNode[10000];
} /** value will always be non-negative. */
public void put(int key, int value) {
int idx = key%10000;
if(nodes[idx]==null){
nodes[idx] = new ListNode(-1,-1);
nodes[idx].next = new ListNode(key,value);
}else{
ListNode pre = find(nodes[idx], key);
if(pre.next == null){
pre.next = new ListNode(key, value);
}else{
pre.next.value = value;
}
}
} /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
int idx = key%10000;
if(nodes[idx] == null) return -1;
else{
ListNode pre = find(nodes[idx], key);
if(pre.next == null) return -1;
else return pre.next.value;
}
} public ListNode find(ListNode root, int key){
ListNode pre = null;
ListNode cur = root;
while(cur!=null && cur.key != key){
pre = cur;
cur = cur.next;
}
return pre;
} /** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
int idx = key%10000;
if(nodes[idx] == null) return;
else{
ListNode pre = find(nodes[idx], key);
if(pre.next == null) return;
else{
pre.next = pre.next.next;
}
}
}
class ListNode{
int key;
int value;
ListNode next;
ListNode(int key, int value){
this.key = key;
this.value = value;
}
}
} /**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/

05 小结

算法专题目前已日更超过四个月,算法题文章167+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

LeetCode算法题-Design HashMap(Java实现)的更多相关文章

  1. LeetCode算法题-Design LinkedList(Java实现)

    这是悦乐书的第300次更新,第319篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第168题(顺位题号是707).设计链表的实现.您可以选择使用单链表或双链表.单链表中的 ...

  2. LeetCode算法题-Design HashSet(Java实现)

    这是悦乐书的第298次更新,第317篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第166题(顺位题号是705).不使用任何内建的hash表库设计一个hash集合,应包含 ...

  3. LeetCode算法题-Heaters(Java实现)

    这是悦乐书的第239次更新,第252篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第106题(顺位题号是475).冬天来了!您在比赛期间的第一份工作是设计一个固定温暖半径 ...

  4. LeetCode算法题-Sqrt(Java实现)

    这是悦乐书的第158次更新,第160篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第17题(顺位题号是69). 计算并返回x的平方根,其中x保证为非负整数. 由于返回类型 ...

  5. LeetCode算法题-Subdomain Visit Count(Java实现)

    这是悦乐书的第320次更新,第341篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第189题(顺位题号是811).像"discuss.leetcode.com& ...

  6. LeetCode算法题-Toeplitz Matrix(Java实现)

    这是悦乐书的第312次更新,第333篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第181题(顺位题号是766).如果从左上角到右下角的每个对角线具有相同的元素,则矩阵是 ...

  7. LeetCode算法题-Longest Word in Dictionary(Java实现)

    这是悦乐书的第303次更新,第322篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第171题(顺位题号是720).给出表示英语词典的字符串单词数组,找到单词中长度最长的单 ...

  8. LeetCode算法题-Degree of an Array(Java实现)

    这是悦乐书的第294次更新,第312篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第162题(顺位题号是697).给定一个由正整数组成的非空数组,该数组的度数被定义为任意 ...

  9. LeetCode算法题-Employee Importance(Java实现)

    这是悦乐书的第291次更新,第309篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第159题(顺位题号是690).定义员工信息的数据结构,其中包括员工的唯一ID,他的重要 ...

随机推荐

  1. spark计算两个DataFrame的差集、交集、合集

    spark 计算两个dataframe 的差集.交集.合集,只选择某一列来对比比较好.新建两个 dataframe : import org.apache.spark.{SparkConf, Spar ...

  2. 【转】ret,retf,iret的区别

    ret RET, and its exact synonym RETN, pop IP or EIP from the stack and transfer control to the new ad ...

  3. Echarts图标自适应问题(已解决)

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

  4. Python爬虫入门教程 6-100 蜂鸟网图片爬取之一

    1. 蜂鸟网图片--简介 国庆假日结束了,新的工作又开始了,今天我们继续爬取一个网站,这个网站为 http://image.fengniao.com/ ,蜂鸟一个摄影大牛聚集的地方,本教程请用来学习, ...

  5. (四)五种IO模型

    基本概念 我们之前编写的套接字程序都是阻塞式的,其实这也是默认的形式.现在我们需要明确一些概念: 用户空间和内核空间 首先要明确,用户启动的应用程序在系统中以一个进程的形式存在,而无论对于网络数据还是 ...

  6. 痞子衡嵌入式:飞思卡尔i.MX RT系列MCU特性介绍(2)- RT1052DVL6性能实测

    大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是飞思卡尔i.MX RT系列MCU的性能. 在前面的文章 i.MXRT微控制器概览 里,痞子衡给大家简介过恩智浦半导体在2017年推出的新 ...

  7. 设计模式-建造者模式(Builder)

    简介: 将一个复杂的对象的构建与它的表示分离,使得同样的构建过程创建出不同的表示. 结构图: 优点: 使得创建代码和表示代码分离,建造者隐藏了该产品是如何组装的,所以若需要改变一个产品内部的表示,只需 ...

  8. Java编程的逻辑 (51) - 剖析EnumSet

    本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...

  9. 【eclipse】eclipse报错:the resource is not on the build path of a java project

    最近在eclipse中,使用svn导入svn上的一个maven项目,但是导入后类的包并没有以源码包的方式显示,而是以普通文件包的方式显示出来,在对类进行F3等操作时就报错:“the resource ...

  10. jsp基础语言-jsp表达式

    1.jsp表达式作用:将动态信息显示在页面中. 2.jsp表达式语法:<%=变量或表达式%> 变量:要在页面显示的值的变量名 表达式:其值由服务器计算,计算结果以字符串的形式发送到客户端 ...