代码拉取完成,页面将自动刷新
public class HashBuck {
static public class Node {
public int key;
public int val;
public Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
public Node[] array = new Node[10];
public int usedSize;
public void push(int key,int val) {
Node node = new Node(key,val);
//1、找到位置
int index = key % array.length;
//2、遍历数组
Node cur = array[index];
while (cur != null) {
if(cur.key == key) {
//更新val
cur.val = val;
return;
}
cur = cur.next;
}
//头插法
node.next = array[index];
array[index] = node;
usedSize++;
if( doLoadFactor() >= 0.75) {
//处理重新哈希
reSize();
}
}
private void reSize() {
Node[] newArray = new Node[array.length*2];
//处理重新哈希
for (int i = 0; i < array.length; i++) {
Node cur = array[i];
while (cur != null) {
int index = cur.key % newArray.length;
//记录下来 之前的cur.next
Node curNext = cur.next;
//进行头插法,插入到新数组
cur.next = newArray[index];
newArray[index] = cur;
cur = curNext;
}
}
//把数据给到原数组 array
array = newArray;
}
private double doLoadFactor() {
return usedSize*1.0 / array.length;
}
public int get(int key) {
//1、找到位置
int index = key % array.length;
//2、遍历数组
Node cur = array[index];
while (cur != null) {
if(cur.key == key) {
return cur.val;
}
cur = cur.next;
}
return -1;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。