리트코드_706
- Separate Chaining(분리 체인법)
- Coalesced Chaining(Open Addressing)(합병 체인법, 오픈 주소법)
class MyHashMap {
private static class Node {
int key;
int value;
Node next;
Node(int key, int value, Node next) {
this.key = key;
this.value = value;
this.next = next;
}
}
private static final int SIZE = 10000;
private Node[] table;
public MyHashMap() {
table = new Node[SIZE];
}
private int hash(int key) {
return key % SIZE;
}
public void put(int key, int value) {
int idx = hash(key);
if (table[idx] == null) {
table[idx] = new Node(key, value, null);
return;
}
Node cur = table[idx];
Node prev = null;
while (cur != null) {
if (cur.key == key) {
cur.value = value;
return;
}
prev = cur;
cur = cur.next;
}
prev.next = new Node(key, value, null);
}
public int get(int key) {
int idx = hash(key);
Node cur = table[idx];
while (cur != null) {
if (cur.key == key) {
return cur.value;
}
cur = cur.next;
}
return -1;
}
public void remove(int key) {
int idx = hash(key);
Node cur = table[idx];
Node prev = null;
while (cur != null) {
if (cur.key == key) {
if (prev == null) {
table[idx] = cur.next;
} else {
prev.next = cur.next;
}
return;
}
prev = cur;
cur = cur.next;
}
}
}