哈希表
哈希表通过元素的存储地址和关键码建立映射关系从而快速找到元素,时间复杂度通常是O(1)
取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B适合范围小且连续的情况
负载因子定义为装入的元素/散列表的长度,负载因子越大造成元素冲突的概率越大,此时只能扩容
闭散列:将元素移到下一个空的位置
开散列/哈希桶:将一个位置定义为链表,这种方法更好,下面来实现它
点击查看代码
//整数
public class HashBuck {
class Node{
int val;
int key;
Node next;
Node(int key,int val){
this.key = key;
this.val = val;
}
}
Node[] array;
public int usedSize;
public static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashBuck(){
array = new Node[10];
}
public void put(int key,int val){
int index = key % array.length;
Node cur = array[index];
while (cur != null){
if(cur.key == key){
cur.val = val;
return;
}
cur = cur.next;
}
Node node = new Node(key,val);
node.next = array[index];
array[index] = node;
usedSize++;
if(doLoadFactor() > DEFAULT_LOAD_FACTOR){
resize();
}
}
private void resize() {
Node[] newArray = new Node[array.length * 2];
for (int i = 0; i < newArray.length; i++) {
Node cur = array[i];
while (cur != null){
int newIndex = cur.key % newArray.length;
Node tmp = cur.next;
cur.next = newArray[newIndex];
newArray[newIndex] = cur;
cur = tmp;
}
}
array = newArray;
}
private float doLoadFactor() {
return usedSize*1.0f / array.length;
}
public int get(int key){
int index = key % array.length;
Node node = array[index];
while (node != null){
if(node.key == key){
return node.val;
}
node = node.next;
}
return -1;
}
}
点击查看代码
public class HashBuck2<K,V> {
class Node<K,V> {
public K k;
public V v;
Node<K,V> next;
Node(K key,V val){
this.k = key;
this.v = val;
}
}
public Node<K,V>[] array;
public static final float DEFAULT_LOAD_FACTOR = 0.75f;
public int usedSize;
public HashBuck2(){
array = (Node<K,V>[])new Node[10];
}
public void put(K key,V val){
int hash = key.hashCode();
int index = hash % array.length;
Node<K,V> cur = array[index];
while (cur != null){
if(cur.k.equals(key)){
cur.v = val;
return;
}
cur = cur.next;
}
Node<K,V> node = new Node<>(key,val);
node.next = array[index];
array[index] = node;
usedSize++;
}
public V getVal(K key){
int hash = key.hashCode();
int index = hash % array.length;
Node<K,V> node = array[index];
while (node != null){
if(node.k.equals(key)){
return node.v;
}
node = node.next;
}
return null;
}
}
浙公网安备 33010602011771号