2024.4.15
- 题目来源
- 我的题解
- 方法一 链表+自定义哈希函数
题目来源
力扣每日一题;题序:706
我的题解
方法一 链表+自定义哈希函数
使用链表存储每个<key,value>。由于题目有限制put的次数不超过10000次,因此对于哈希函数的设计为:hashCode(key)%10000
class MyHashMap {class LinkedList{int[] val;LinkedList next;public LinkedList(){}public LinkedList(int[] v){val=v;}public int size(){LinkedList root=this;int sz=0;while(root!=null){sz++;root=root.next;}return sz;}}private LinkedList[] map;int n=10001;public MyHashMap() {map=new LinkedList[n];}public void put(int key, int value) {int index=myHash(key);//对应位置还未初始化if(map[index]==null){map[index]=new LinkedList(new int[]{key,value});//对应位置的长度为0}else if(map[index].size()==0){map[index]=new LinkedList(new int[]{key,value});}else{LinkedList root=map[index];//链首就是keyif(root.val[0]==key){root.val[1]=value;}else{while(root.next!=null&&root.next.val[0]!=key){root=root.next;}//在链中存在keyif(root.next!=null){root.next.val[1]=value;//链中不存在key}else{root.next=new LinkedList(new int[]{key,value});}}}}public int get(int key) {int index=myHash(key);//对应位置还未初始化if(map[index]==null||map[index].size()==0){return -1;}else{LinkedList root=map[index];//链首就是keyif(root.val[0]==key){return root.val[1];}else{while(root.next!=null&&root.next.val[0]!=key){root=root.next;}//在链中存在keyif(root.next!=null){return root.next.val[1];//链中不存在key}else{return -1;}}}}public void remove(int key) {int index=myHash(key);//对应位置还未初始化||对应位置的长度为0if(map[index]==null||map[index].size()==0){return ;}else{LinkedList root=map[index];//链首就是keyif(root.val[0]==key){map[index]=root.next;}else{while(root.next!=null&&root.next.val[0]!=key){root=root.next;}//在链中存在keyif(root.next!=null){root.next=root.next.next;//链中不存在key}}}}private int myHash(int key){int iHash=Integer.hashCode(key);return iHash%(n-1);}
}
有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~