题目
不使用任何内建的哈希表库设计一个哈希映射(HashMap)。
1.MyHashMap() 用空映射初始化对象
2.void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。如果 key 已经存在于映射中,则更新其对应的值 value 。
3.int get(int key) 返回特定的 key 所映射的 value ;如果映射中不包含 key 的映射,返回 -1 。
4.void remove(key) 如果映射中存在 key 的映射,则移除 key 和它所对应的 value 。
代码
package LeeCode._20210314_706;
class node{
int key;
int value;
node next;
public node(int key, int value) {
this.key = key;
this.value = value;
}
public node() {}
}
public class MyHashMap {
node[] arr;
int size;
double loadFactor = 0.75;
/** Initialize your data structure here. */
public MyHashMap() {
arr = new node[1<<10];
size = 0;
}
public int hashcode(int key,int length){//扩容的时候,size是要变的
return key & (length-1);/
}
/** value will always be non-negative. */
public void put(int key, int value) {
if(++size > arr.length * loadFactor){
resize();
}
int index = hashcode(key,arr.length);
node cur = new node(key,value);
node head = arr[index];
//1.
if(head == null){
head = new node();
arr[index] = head;?????????????????????????????
head.next = cur;
}else{
//2.
node h1 = head.next;
while(h1!=null){
if(h1.key == key){
h1.value = value;
return;
}
h1 = h1.next;
}
//3.
h1 = head.next;
head.next = cur;
cur.next = h1;
}
}
/** 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 index = hashcode(key,arr.length);
node head = arr[index];
//1.
if(head == null){
return -1;
}else{
//2.
node h1 = head.next;
while(h1!=null){
if(h1.key == key){
return h1.value;
}
h1 = h1.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 index = hashcode(key,arr.length);
node head = arr[index];
//1.
if(head == null){
return ;
}
//2.
node h1 = head.next;
node pre = head;
while(h1!=null){
if(h1.key == key){
pre.next = h1.next;
size--;
return ;
}
h1 = h1.next;
pre = pre.next;
}
return ;
}//遍历一下,就能处理所有元素
//新的hashcode怎么办?内层遍历的时候有了各自的key,重新分家
public void resize(){
node[] arr2 = new node[arr.length<<1];//先初始化
for(int i=0;i<size;i++){//这层遍历是要转移所有的节点
node head = arr[i];
if(head == null){
continue;
}
node h1 = head.next;
while(h1.next != null){//这层遍历是把挂在当前索引下的元素都搬家
int key = h1.key;
int newindex = hashcode(key,arr.length<<1);
//1.
if(arr2[newindex] == null){
arr2[newindex] = new node();
//arr2[newindex].next = new node(h1.key,h1.value);
arr2[newindex].next = h1;
}else{
//2.
node tmp = new node(key, h1.value);
tmp.next = arr2[newindex].next;
h1.next = tmp;
//我才发现当前列表不可能会有重复的键,所以直接插在头上
}
}
}
}
}