哈希表结构
谷歌的一道关于哈希表的面试题
- 有一个公司,当有新员工来报道时,要求将该员工信息录入(id,姓名,年龄,住址...),通过id可以查到该员工详细信息,要求不使用数据库,速度越快越好。
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;
}
}
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;
}
}
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;
}