数据结构与算法(七)哈希表

252 阅读1分钟

哈希表结构

  • 数组+链表
  • 数组+二叉树

谷歌的一道关于哈希表的面试题

  • 有一个公司,当有新员工来报道时,要求将该员工信息录入(id,姓名,年龄,住址...),通过id可以查到该员工详细信息,要求不使用数据库,速度越快越好。
//hashtable的类

class HashTable{
    public EmpLinkedList[] empArr;
    public int size;

    public HashTable(int size) {
        this.size=size;
        empArr=new EmpLinkedList[size];
        for (int i = 0; i <size ; i++) {
            empArr[i]=new EmpLinkedList();
        }
    }

    public Employee query(int id){
        int num=hash(id);
        Employee emp= empArr[num].query(id);
        return emp;
    }

    public void add(Employee emp){
        int num=hash(emp.id);
        empArr[num].add(emp);
    }

    public void show(){
        for (int i = 0; i <size ; i++) {
            empArr[i].show(i);
        }
    }

    //编写散列函数,如取模法
    private int hash(int id){
        return id%size;
    }
}

//employee类

class Employee{
    public int id;
    public String name;
    public Employee next;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

class EmpLinkedList{
    public Employee head;

    //添加雇员到链表
    public void add(Employee emp){
        if(head==null){
            head=emp;
            return;
        }
        Employee temp=head;
        while (true){
            if(temp.next==null){
                break;
            }
            temp.next=temp;
        }
        temp.next=emp;
    }

    //遍历链表的雇员信息
    public void show(int no){
        if(head==null){
            System.out.println("第"+no+"条链表为空");
            return;
        }
        Employee temp=head;
        while (true){
            System.out.println("第"+no+"条链表为: "+temp.id+";"+temp.name);
            if(temp.next==null){
                break;
            }
            temp.next=temp;
        }
    }

    //根据id查找员工
    public Employee query(int id){
        while (true){
            if(head==null){
                break;
            }
            Employee temp=head;
            //
            if(temp.id==id){
                return temp;
            }
            //
            if(temp.next==null){
                break;
            }
            temp.next=temp;
        }
        return null;
    }