Hash基础和队列基础

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;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值