【Java数据结构】哈希表详解

===================

开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子 集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中。

static class Node {

public int key;

public int val;

public Node next;

public Node(int key, int val) {

this.key = key;

this.val = val;

}

}

private Node[] array;

public int usedSize;

public HashBucket() {

this.array = new Node[10];

this.usedSize = 0;

}

public void put(int key,int val){

int index = key % this.array.length;

Node cur = array[index];

while (cur != null){

if(cur.val == key){

cur.val = val;

return;

}

cur = cur.next;

}

//头插法

Node node = new Node(key,val);

node.next = array[index];

array[index] = node;

this.usedSize++;

if(loadFactor() >= 0.75){

resize();

}

}

public int get(int key) {

//以什么方式存储的 那就以什么方式取

int index = key % this.array.length;

Node cur = array[index];

while (cur != null) {

if(cur.key == key) {

return cur.val;

}

cur = cur.next;

}

return -1;//

}

public void resize(){

Node[] newArray = new Node[2*this.array.length];

for (int i = 0; i < this.array.length; i++){

Node cur = array[i];

Node curNext = null;

while (cur != null){

curNext = cur.next;

int index = cur.key % newArray.length;

cur.next = newArray[i];

newArray[i] = cur;

cur = curNext.next;

cur = curNext;

}

}

this.array = newArray;

}

6,完整代码

==========

class HashBucket {

static class Node {

public int key;

public int val;

public Node next;

public Node(int key, int val) {

this.key = key;

this.val = val;

}

}

private Node[] array;

public int usedSize;

public HashBucket() {

this.array = new Node[10];

this.usedSize = 0;

}

public void put(int key,int val) {

//1、确定下标

int index = key % this.array.length;

//2、遍历这个下标的链表

Node cur = array[index];

while (cur != null) {

//更新val

if(cur.key == key) {

cur.val = val;

return;

}

cur = cur.next;

}

//3、cur == null 当前数组下标的 链表 没要key

Node node = new Node(key,val);

node.next = array[index];

array[index] = node;

this.usedSize++;

//4、判断 当前 有没有超过负载因子

if(loadFactor() >= 0.75) {

//扩容

resize();

}

}

public int get(int key) {

//以什么方式存储的 那就以什么方式取

int index = key % this.array.length;

Node cur = array[index];

while (cur != null) {

if(cur.key == key) {

return cur.val;

}

cur = cur.next;

}

return -1;//

}

public double loadFactor() {

return this.usedSize*1.0 / this.array.length;

}

public void resize(){

Node[] newArray = new Node[2*this.array.length];

for (int i = 0; i < this.array.length; i++){

Node cur = array[i];

Node curNext = null;

  • 20
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值