数据结构和算法:哈希表

哈希表(Hash Table)是一种非常重要的数据结构,它利用哈希函数将键(Key)映射到存储桶(Bucket)的位置,从而实现快速的插入、查找和删除操作。在Java中,哈希表通常由HashMap类实现。

以下是一个简单的哈希表实现,仅用于教学目的,不建议在生产环境中使用。

首先,定义一个哈希函数,它可以根据键计算哈希值:

java 复制代码
public class HashTable {
    private static final int DEFAULT_CAPACITY = 16;
    private int capacity;
    private List<LinkedList<KeyValuePair>> buckets;

    // 简单的哈希函数
    private int hash(int key) {
        return key % capacity;
    }

    // 键值对类
    private static class KeyValuePair {
        int key;
        Object value;

        KeyValuePair(int key, Object value) {
            this.key = key;
            this.value = value;
        }
    }

    public HashTable() {
        this(DEFAULT_CAPACITY);
    }

    public HashTable(int capacity) {
        this.capacity = capacity;
        buckets = new ArrayList<>(capacity);
        for (int i = 0; i < capacity; i++) {
            buckets.add(new LinkedList<>());
        }
    }
}

然后,我们可以实现插入、查找和删除操作:

java 复制代码
public class HashTable {
    // ... 省略之前的代码 ...

    // 插入键值对
    public void put(int key, Object value) {
        int index = hash(key);
        LinkedList<KeyValuePair> bucket = buckets.get(index);
        for (KeyValuePair pair : bucket) {
            if (pair.key == key) {
                pair.value = value; // 更新值
                return;
            }
        }
        bucket.add(new KeyValuePair(key, value)); // 插入新的键值对
    }

    // 获取键对应的值
    public Object get(int key) {
        int index = hash(key);
        LinkedList<KeyValuePair> bucket = buckets.get(index);
        for (KeyValuePair pair : bucket) {
            if (pair.key == key) {
                return pair.value;
            }
        }
        return null; // 未找到键
    }

    // 删除键值对
    public void remove(int key) {
        int index = hash(key);
        LinkedList<KeyValuePair> bucket = buckets.get(index);
        Iterator<KeyValuePair> iterator = bucket.iterator();
        while (iterator.hasNext()) {
            KeyValuePair pair = iterator.next();
            if (pair.key == key) {
                iterator.remove(); // 删除键值对
                return;
            }
        }
    }
}

注意:

  1. 这个实现使用了简单的取模运算作为哈希函数,但在实际中,哈希函数的设计要复杂得多,需要考虑哈希冲突的解决、哈希分布的均匀性等问题。
  2. 当哈希表中的元素过多时,可能会导致哈希冲突加剧,影响性能。此时,可以通过重新分配更大的空间并重新哈希所有元素来解决这个问题,这通常被称为"扩容"或"再哈希"。
  3. Java中的HashMap类使用了更复杂的数据结构和算法,包括链表和红黑树来解决哈希冲突和保持性能。这个简单的哈希表实现仅用于教学目的,无法与HashMap的性能和功能相比。
相关推荐
小白菜又菜17 分钟前
Leetcode 646. Maximum Length of Pair Chain
算法·leetcode·职场和发展
ヾ慈城1 小时前
【数据结构 - 二叉树】
c语言·数据结构·算法·链表
闲仁人1 小时前
数据结构预科
数据结构
卡戎-caryon1 小时前
【项目实践】贪吃蛇
c语言·数据结构·算法
PeterClerk1 小时前
PCA算法降维代码示例
人工智能·算法·机器学习·pca
计算机平台作业答案讲解2 小时前
QT实现GIF动图显示(小白版,可直接copy使用)
服务器·开发语言·数据结构·数据库·c++·qt·动态规划
冲鸭嘟嘟可2 小时前
【数据结构】使用C语言 从零实现一个栈的数据结构
c语言·数据结构·算法
小白菜又菜2 小时前
Leetcode 516. Longest Palindromic Subsequence
算法·leetcode·职场和发展
℡☞小白☜ღ2 小时前
信号量(semaphore)
算法