链表-Java-力扣706. 设计哈希映射

这篇博客介绍了一个自定义的哈希映射实现,使用ArrayList数组存储Map对象,每个Map包含key和value。哈希映射通过BUCKETS(1009)作为桶的数量,使用哈希函数计算key的索引。博客详细展示了put、get和remove操作的实现,通过对哈希桶中元素的迭代来完成相应操作。
摘要由CSDN通过智能技术生成

1. 题目

题目链接706. 设计哈希映射

2. 思路

主要是利用ArrayList数组,保存自己写的类Map,里面有key和value,然后设置一个合理的长度BUCKETS,生成哈希函数的值,每次将key转换为hash值,然后使用Iterator遍历做删除,插入和查询操作即可。

3. 代码

class MyHashMap {

    /** Initialize your data structure here. */
    private class Map {
        public int key;
        public int value;
        public Map(int key, int value) {
            this.key = key;
            this.value = value;
        }
        public Map() {}
    }

    private static final int BUCKETS = 1009;
    private ArrayList[] hashMap;

    public MyHashMap() {
        hashMap = new ArrayList[BUCKETS];
        for (int i = 0; i < BUCKETS; i++) {
            hashMap[i] = new ArrayList<Map>();
        }
    }
    
    /** value will always be non-negative. */
    public void put(int key, int value) {
        int index = hash(key);
        Iterator<Map> iterator = hashMap[index].iterator();
        while (iterator.hasNext()) {
            Map map = iterator.next();
            if (map.key == key) {
                map.value = value;
                return;
            }
        }
        hashMap[index].add(new Map(key, value));
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    public int get(int key) {
        int index = hash(key);
        Iterator<Map> iterator = hashMap[index].iterator();
        while (iterator.hasNext()) {
            Map map = iterator.next();
            if (map.key == key) {
                return map.value;
            }
        }
        return -1;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    public void remove(int key) {
        int index = hash(key);
        Iterator<Map> iterator = hashMap[index].iterator();
        while (iterator.hasNext()) {
            Map map = iterator.next();
            if (map.key == key) {
                hashMap[index].remove(map);
                return;
            }
        }
    }

    public int hash(int key) {
        return key % BUCKETS;
    }
}

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap obj = new MyHashMap();
 * obj.put(key,value);
 * int param_2 = obj.get(key);
 * obj.remove(key);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值