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; } } }
  • 相关阅读:
    HDU 5528 Count a * b 欧拉函数
    HDU 5534 Partial Tree 完全背包
    HDU 5536 Chip Factory Trie
    HDU 5510 Bazinga KMP
    HDU 4821 String 字符串哈希
    HDU 4814 Golden Radio Base 模拟
    LA 6538 Dinner Coming Soon DP
    HDU 4781 Assignment For Princess 构造
    LA 7056 Colorful Toy Polya定理
    LA 6540 Fibonacci Tree
  • 原文地址:https://www.cnblogs.com/steve-jiang/p/13286057.html
Copyright © 2011-2022 走看看