1、题目:https://leetcode-cn.com/problems/design-hashmap/
2、功能:实现哈希表,也就是HashMap的底层实现
(1)我们查看HashMap的源码:
3、代码
package com.leetcode;
/**
* HashMap 是由 数组 + 单链表 组成
* @author zhou
*
*/
public class 设计哈希映射_2 {
class MyHashMap {
class Node{
private int key;
private int val;
private Node next;
public Node(int key,int val){
this.key = key;
this.val = val;
}
}
private static final int N = 100011;
Node[] table = null;
/** Initialize your data structure here. */
public MyHashMap() {
this.table = new Node[N]; //初始化,数组中节点为Null
}
/** value will always be non-negative. */
public void put(int key, int value) {
Node cur = new Node(key,value);
int idx = key % N;
if(table[idx] == null){ //此处数组元素为空,则直接将新节点放进去
table[idx] = cur;
}else{ //此处数组元素不为空,则遍历数组下标所对应的链表
Node tmp = table[idx];
Node last = null;
while(tmp != null){
//1.键重复,则覆盖更新
if(tmp.key == key){
tmp.val = value;
break;
}else{ //2.键不存在不重复,则遍历下一个;
last = tmp;
tmp = tmp.next;
}
}
//则插入到链表末尾
if(tmp == null){
last.next = cur;
}
}
}
/** 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 % N;
if(table[idx] == null) return -1;
Node tar = table[idx];
while(tar != null){ //索引到数组中对应的下标位置
if(tar.key == key){
return tar.val;
}
tar = tar.next; //继续对数组中对应的下标位置 的链表进行索引链表
}
return -1;
}
/** 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 % N;
if (table[idx] == null) return;
Node tar = table[idx];
Node pre = null;
Node after = null;
while(tar != null){ //索引到数组中对应的下标位置
//继续对数组中对应的下标位置 的链表进行索引链表
while(tar.key != key){
pre = tar;
tar = tar.next;
}
//退出循环时,此时的tar正是目标节点
after = tar.next;
pre.next = after;
}
}
}
}