Hash基础
hash的存储计算公式为模运算,若数组array存放1到15到一个大小为7的hash表中,存储位置计算公式为:index=number mod 7
hash索引:0 1 2 3 4 5 6
存入的值 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15
hash查找的时间复杂度为O(1)。
若要查找13则index=13%7=6,直接访问array[6],时间复杂度为O(1)。
碰撞处理方法
当不同的输入值算出的存储位置相同时,称为碰撞,例如1和8的index均为1。
开放定址法
发生了碰撞就寻找下一个空的地址。
hash索引:0 1 2 3 4 5 6
已存入值 1 2 4
存入8 -> -> 8
链地址法
将Hash表的每个单元作为链表的头结点,出现碰撞就将输入值作为index位置的链表的下一个结点。
hash索引:
0->
1->1->8->15
2->2->9
3->
4
5->5
6
hash数组的长度必须为2的n次幂。
hash扩容机制:到达hash长度的0.75就将长度拓展为原来的2倍。
队列基础
队列为先进先出,先入队的先出队。
队列实现
public class LinkQueue {
private Node front;//头结点
private Node rear;
private int size;
public LinkQueue(){
this.front = new Node(0);
this.rear = new Node(0);
}
public void push(int value){
Node newNode = new Node(value);
Node temp = front;
while (temp!=null){
temp = temp.next;
}
temp.next = newNode;
rear = newNode;
size++;
}
public int pull(){
if (front.next==null){
System.out.println("队列为空");
}
Node firstNode = front.next;
front.next = firstNode.next;
size--;
return firstNode.value;
}
public void traverse(){
Node temp = front.next;
while (temp!=null){
System.out.print(temp.value+"\t");
temp = temp.next;
}
}
}
class Node {
public int value;
public Node next;
public Node(int x){
value = x;
next = null;
}
}