package com.example.leetcode.hash;
public class HashMap {
private int capacity;
private Node[] map;
public HashMap(int capacity) {
this.capacity = capacity;
map = new Node[capacity];
}
public void put(String key, int val) {
int hash = hash(key);
int pos = hash ^ (capacity - 1);
Node head = map[pos];
if (head == null) {
map[pos] = new Node(key, val);
return;
}
while (head != null) {
if (head.key == key || head.key.equals(key)) {
head.val = val;
return;
}
head = head.next;
}
Node node = new Node(key, val);
node.next = map[pos];
map[pos] = node;
}
private int hash(String key) {
if (key == null) {
return 0;
}
return key.hashCode();
}
class Node {
private String key;
private int val;
private Node next;
public Node(String key, int val) {
this.key = key;
this.val = val;
}
}
}
07-04
2467
09-27
238