返回
数据结构面试题:零基础学会hashtable
见解分享
2024-01-21 16:05:25
一、哈希表概述
哈希表(HashTable)是一种数据结构,它使用键值对来存储数据,其中键是唯一标识符,值是存储的数据。哈希表与数组相似,但它不像数组那样使用索引来访问元素,而是使用键。这意味着哈希表可以以比数组更快的速度查找和检索数据。
二、哈希表用途
哈希表是轻量级的缓存产品,广泛应用于各种场景,如:
- 快速查找数据:哈希表可以快速查找数据,这使得它非常适合用于需要快速访问数据的应用程序。
- 存储临时数据:哈希表可以存储临时数据,这使得它非常适合用于需要存储数据并在稍后删除的应用程序。
- 实现缓存:哈希表可以实现缓存,这使得它非常适合用于需要快速访问数据的应用程序。
三、谷歌面试题
谷歌的面试题中经常会考到哈希表。其中一个常见的题目是要求实现一个哈希表。实现哈希表的方法有很多种,这里介绍一种使用数组和链表的实现方法。
四、代码实现
第一步:编写雇员类Emp.java
public class Emp {
private int id;
private String name;
private double salary;
public Emp(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
第二步:编写单个链表类
public class Node {
private Emp emp;
private Node next;
public Node(Emp emp) {
this.emp = emp;
}
public Emp getEmp() {
return emp;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
第三步:编写哈希表类
public class HashTable {
private Node[] table;
private int size;
public HashTable(int size) {
this.table = new Node[size];
this.size = size;
}
public void put(Emp emp) {
int index = hash(emp.getId());
Node node = new Node(emp);
node.setNext(table[index]);
table[index] = node;
}
public Emp get(int id) {
int index = hash(id);
Node node = table[index];
while (node != null) {
if (node.getEmp().getId() == id) {
return node.getEmp();
}
node = node.getNext();
}
return null;
}
private int hash(int id) {
return id % size;
}
}
第四步:测试哈希表
public class TestHashTable {
public static void main(String[] args) {
HashTable hashTable = new HashTable(10);
hashTable.put(new Emp(1, "张三", 10000.0));
hashTable.put(new Emp(2, "李四", 20000.0));
hashTable.put(new Emp(3, "王五", 30000.0));
Emp emp = hashTable.get(1);
System.out.println(emp.getName()); // 输出:张三
}
}
五、总结
本文介绍了哈希表的数据结构,哈希表用途,哈希表代码实现。希望本文对您有所帮助。