效果好的徐州网站建设,做网站用虚拟服务器可以吗,wordpress用旧的编辑器,蚌埠网页设计培训2024.4.15 题目来源我的题解方法一 链表自定义哈希函数 题目来源
力扣每日一题#xff1b;题序#xff1a;706
我的题解
方法一 链表自定义哈希函数 使用链表存储每个key,value。由于题目有限制put的次数不超过10000次#xff0c;因此对于哈希函数的设计为#… 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){valv;}public int size(){LinkedList rootthis;int sz0;while(root!null){sz;rootroot.next;}return sz;}}private LinkedList[] map;int n10001;public MyHashMap() {mapnew LinkedList[n];}public void put(int key, int value) {int indexmyHash(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 rootmap[index];//链首就是keyif(root.val[0]key){root.val[1]value;}else{while(root.next!nullroot.next.val[0]!key){rootroot.next;}//在链中存在keyif(root.next!null){root.next.val[1]value;//链中不存在key}else{root.nextnew LinkedList(new int[]{key,value});}}}}public int get(int key) {int indexmyHash(key);//对应位置还未初始化if(map[index]null||map[index].size()0){return -1;}else{LinkedList rootmap[index];//链首就是keyif(root.val[0]key){return root.val[1];}else{while(root.next!nullroot.next.val[0]!key){rootroot.next;}//在链中存在keyif(root.next!null){return root.next.val[1];//链中不存在key}else{return -1;}}}}public void remove(int key) {int indexmyHash(key);//对应位置还未初始化||对应位置的长度为0if(map[index]null||map[index].size()0){return ;}else{LinkedList rootmap[index];//链首就是keyif(root.val[0]key){map[index]root.next;}else{while(root.next!nullroot.next.val[0]!key){rootroot.next;}//在链中存在keyif(root.next!null){root.nextroot.next.next;//链中不存在key}}}}private int myHash(int key){int iHashInteger.hashCode(key);return iHash%(n-1);}
}有任何问题欢迎评论区交流欢迎评论区提供其它解题思路代码也可以点个赞支持一下作者哈~