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; } } }
  • 相关阅读:
    box-shadow做出一条线两种颜色
    调取手机摄像头拍照并获取拍得的照片
    PHP请求第三方接口的函数
    PHP mysqli类
    PHP CI框架最近学到的内容
    GE_OG_CALC_COLUMN_EMPTY
    Oracle分区知识
    创建理想的SEQUENCE和自增长的trigger
    Oracle的大数据类型,BIG DATA TYPE
    FOREIGN KEY相关
  • 原文地址:https://www.cnblogs.com/steve-jiang/p/13286057.html
Copyright © 2011-2022 走看看