Design HashMap | LeetCode 706 | C++, Java, Python

preview_player
Показать описание

**** Best Books For Data Structures & Algorithms for Interviews:**********
*****************************************************************************

Design HashMap | Leetcode 706
Facebook Coding Interview question,
google coding interview question,
leetcode,
Design HashMap,
Design HashMap C++,
Design HashMap Java,
Design HashMap python,
Design HashMap solution,
706. Design HashMap,

#CodingInterview #LeetCode #Google #Amazon
Рекомендации по теме
Комментарии
Автор

Below is what I did!

class MyHashMap {

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

Node[] bucket;
int maxSize;

public MyHashMap() {
maxSize = 16;
bucket = new Node[maxSize];
}

private int hashCode(int a) {
return a % maxSize;
}

private boolean equals(Node n, int key) {
if(n.key == key) return true;
return false;
}

public void put(int key, int value) {

int getHash = hashCode(key);
Node head = bucket[getHash];

//check if already present
Node curr = head;
while(curr != null) {
if(equals(curr, key)) {
curr.value = value;
return;
}
curr = curr.next;
}
//if not present
Node temp = new Node(key, value);
temp.next = head;
head = temp;
bucket[getHash] = head;
}

public int get(int key) {

int getHash = hashCode(key);
Node head = bucket[getHash];
if(head == null) return -1;

Node curr = head;
while(curr != null) {
if(equals(curr, key)) {
return curr.value;
}
curr = curr.next;
}
return -1;
}

public void remove(int key) {
int getHash = hashCode(key);
Node head = bucket[getHash];
if(head == null) return;

if(equals(head, key))
bucket[getHash] = head.next;
else{
Node curr = head;
while(curr != null) {
if(curr.next != null && equals(curr.next, key)) {
curr.next = curr.next.next;
}
curr = curr.next;
}
bucket[getHash] = head;
}
}
}

sandeepraja
Автор

Sir, I can't understand how you initialized the vector in the constructor. I am doing same but instead to that I am using memset in the constructor and it's not working.Please explain, Thank you.

AB-frqn
Автор

Thanks for the solution. But when I use this java answer. The compiler will have an error that says: Index 250005 out of bounds for length 100001; Is this because the lc change the statement of the question? Thanks!

sihanyang
Автор

this is good . but you are not using Hashing technique here . Like Linear probing and chaining . using hash fucntion, we can map key value pairs using array of buckets of some size. Using this approach time complexity depends upon the load factor.

Thank you.

praveenj
Автор

Could you please tell us the other method as well

abhisheksuryavanshi
Автор

This solution cannot be used in interviews....
We were expecting space optimized version.

dataman
join shbcf.ru