Design a HashMap without using any built-in hash table libraries.

To be specific, your design should include these functions:

  • put(key, value): Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.
  • get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • remove(key): Remove the mapping for the value key if this map contains the mapping for the key.
class MyHashMap {
    class Node {
        public int key;
        public int value;
        Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private Node[] nodes;
    private int size = 100;

    /** Initialize your data structure here. */
    public MyHashMap() {
        nodes = new Node[this.size];
    }

    /** value will always be non-negative. */
    public void put(int key, int value) {
        int index = key % this.size;
        if(nodes[index] == null) {
            nodes[index] = new Node(key, value);
        } else {
            Node p = nodes[index];
            while(p != null && p.key != key) {
                p = p.next;
            }

            if(p == null) {
                Node n = new Node(key, value);
                n.next = this.nodes[index];
                this.nodes[index] = n;
            } else {
                p.value = 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) {
        int index = key % this.size;
        if(this.nodes[index] == null)
            return -1;

        Node p = this.nodes[index];
        while(p != null && p.key != key)
            p = p.next;
        if(p == null)
            return -1;
        return p.value;
    }

    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    public void remove(int key) {
        int index = key % this.size;
        if(this.nodes[index] == null)
            return;

        Node p = this.nodes[index];
        if(p.key == key) {
            this.nodes[index] = this.nodes[index].next;
            return;
        }

        while(p.next != null && p.next.key != key)
            p = p.next;

        if(p.next == null)
            return;

        p.next = p.next.next;
    }
}

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

results matching ""

    No results matching ""