Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created August 15, 2023 14:54
Show Gist options
  • Select an option

  • Save carefree-ladka/50c1f8c76794733967f3b055942b070b to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/50c1f8c76794733967f3b055942b070b to your computer and use it in GitHub Desktop.
Leetcode HashMap Using LinkedList
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
class LinkedList {
constructor() {
this.head = null;
}
addOrUpdate = (key, value) => {
if (!this.head) {
this.head = new Node(key, value);
return;
}
let current = this.head;
while (current) {
if (current.key === key) {
current.value = value;
return;
}
if (!current.next) {
current.next = new Node(key, value);
return;
}
current = current.next;
}
};
get = () => {
let current = this.head;
while (current) {
if (current.key === key) {
return current.value;
}
current = current.next;
}
return -1;
};
remove = () => {
if (!this.head) return;
if (this.head.key === key) {
this.head = this.head.next;
return;
}
let current = this.head;
while (current.next) {
if (current.next.key === key) {
current.next = current.next.next;
return;
}
current = current.next;
}
};
}
class HashMap {
constructor(size = 100) {
this.size = 100;
this.map = new Array(size).fill(null).map(() => new LinkedList());
}
#hashCode = (key) => {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = hash + (key.charCodeAt(i) % this.size);
}
return hash;
};
put = (key, value) => {
const index = this.#hashCode(key);
this.map[index].addOrUpdate(key, value);
};
get = (key) => {
const index = this.#hashCode(key);
return this.map[index].get(key);
};
remove = () => {
const index = this.#hashCode(key);
return this.map[index].remove(key);
};
contains = () => {
const index = this.#hashCode(key);
return this.map[index].get(key) !== undefined;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment