Leetcode设计hashmap

不使用任何内建的哈希表库设计一个哈希映射

具体地说,你的设计应该包含以下的功能
put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。
remove(key):如果映射中存在这个键,删除这个数值对。

示例:

MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);
hashMap.put(2, 2);
hashMap.get(1); // 返回 1
hashMap.get(3); // 返回 -1 (未找到)
hashMap.put(2, 1); // 更新已有的值
hashMap.get(2); // 返回 1
hashMap.remove(2); // 删除键为2的数据
hashMap.get(2); // 返回 -1 (未找到)

注意:
所有的值都在 [1, 1000000]的范围内。
操作的总数目在[1, 10000]范围内。
不要使用内建的哈希库。

package com.oracle.test;

public class MyHashMap {

    int [] values = new int[1000001];
    public MyHashMap() {
        for(int i = 0;i<values.length;i++) {
            values[i] = -1;
        }
    }
    
    /** value will always be non-negative. */
    public void put(int key, int value) {
        values[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) {
        return values[key];
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    public void remove(int key) {
        values[key] = -1;
    }
}
图片.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 这次我和大家一起学习HashMap,HashMap我们在工作中经常会使用,而且面试中也很频繁会问到,因为它里...
    liangzzz阅读 8,094评论 7 102
  • 如果说Java的HashMap是数组+链表,那么JDK 8之后就是数组+链表+红黑树组成了HashMap。 在之前...
    Java_Explorer阅读 1,025评论 1 5
  • 前言 HashMap HashMap类继承图 HashMap属性 HashMap构造函数HashMap(int i...
    HikariCP阅读 1,928评论 0 5
  • 七天训感悟之一 钱武晖 当初新进入向阳英语时,我认认真真地参加了七天训。之后的几...
    雨过天晴love阅读 355评论 0 0
  • 我很喜欢,我现在这样的状态,虽然自己还是不够好。但是其他想想,真的很温馨。 来法一年半,最担心的情感问题,朋友会越...
    厄悟黑阅读 460评论 0 0

友情链接更多精彩内容