zoukankan      html  css  js  c++  java
  • 手写hashMap(非红黑树)

    package cn.learn.datastructor.leetcode;
    
    import java.util.Iterator;
    import java.util.LinkedList;
    
    public class MyHashMap {
       // 数量可以是动态的,此时需要rehash了
    int size = 10000; Entry[] table; /** Initialize your data structure here. */ public MyHashMap() { table = new Entry[size]; } /** value will always be non-negative. */ public void put(int key, int value) { int index; Entry e; Node n = new Node(key, value); if ((e = table[index = hash(key)]) == null) { e = new Entry(); e.addNode(n); table[index] = e; } else { Iterator<Node> iterator = e.nodeList.iterator(); while (iterator.hasNext()) { Node next = iterator.next(); if (next.key == key) { next.value = value; return; } } e.addNode(n); } } private int hash(int key) { return key % size; } /** 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) { Entry e; if ((e = table[hash(key)]) != null) { Iterator<Node> iterator = e.nodeList.iterator(); while (iterator.hasNext()) { Node next = iterator.next(); if (next.key == key) { return next.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) { Entry e; if ((e = table[hash(key)]) != null) { Iterator<Node> iterator = e.nodeList.iterator(); while (iterator.hasNext()) { Node next = iterator.next(); if (next.key == key) { e.nodeList.remove(next); return; } } } } class Entry<Node> { LinkedList<Node> nodeList; void addNode(Node n) { if (nodeList == null) { nodeList = new LinkedList<>(); } nodeList.addLast(n); } } class Node{ int key; int value; public Node(int key, int value) { this.key = key; this.value = value; } } }
  • 相关阅读:
    magic_quotes_gpc(魔术引号开关)
    获取文件绝对路径:__FILE__与 $_SERVER[SCRIPT_FILENAME''] 的 区别
    小程序wx:key中的关键字*this
    swiper 更改indicator-dots 属性 隐藏面板指示点
    B站视频下载
    makefile教程
    Qt 中配置 c99的问题
    C语言编译过程及相关文件
    go语言入门(10)并发编程
    go语言入门(9)文本文件处理
  • 原文地址:https://www.cnblogs.com/steve-jiang/p/13286057.html
Copyright © 2011-2022 走看看