LeetCode -- Design HashMap

 

题意及思路

题意:自己设计一个HashMap(不适用内置实现)

思路:当前思路比较简单、暴力(下次读HashMap的源码后,再将其修改,优化)。思路是创建一个百万级别的数组,构造一个MyHashMap时,将数组中的value设为整型最小值(几乎不会使用的值)。加入就修改其值,删除就将值重置为整型最小值。暴力法。。。

 

代码

class MyHashMap {
    private final int base = 1000000;
    private int len = 1000050;
    private int nums[] = new int[len];

    /** Initialize your data structure here. */
    public MyHashMap() {
        for(int i=0;i<len;i++) nums[i] = Integer.MIN_VALUE;
    }
    
    /** value will always be non-negative. */
    public void put(int key, int value) {
        nums[key%base] = 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) {
        if(nums[key%base]==Integer.MIN_VALUE) return -1;
        return nums[key%base];
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    public void remove(int key) {
        nums[key%base] = Integer.MIN_VALUE;
    }
}

/**
 * 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);
 */

 

转载于:https://www.cnblogs.com/kyrie211/p/11217125.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值