-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathMyHashMap.java
More file actions
91 lines (73 loc) · 2.51 KB
/
MyHashMap.java
File metadata and controls
91 lines (73 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Time Complexity : Time complexity is O(1) on average and O(n) in worst case
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
// This custom HashMap uses an array of 1000 buckets where each bucket is a linked list to store key-value pairs, and it uses a simple hash function (key % 1000) to decide which bucket to put data in. When you add, get, or remove items, it finds the right bucket and then searches through the linked list to handle the operations.
class MyHashMap {
static class Node {
private int key;
private int value;
private Node next;
Node(int key, int value) {
this.key = key;
this.value = value;
this.next = null;
}
}
private static final int SIZE = 1000;
private Node[] buckets;
public MyHashMap() {
buckets = new Node[SIZE];
}
private int getHash(int key) {
return key % SIZE;
}
public void put(int key, int value) {
int index = getHash(key);
if (buckets[index] == null) {
buckets[index] = new Node(-1, -1);
}
Node previousNode = buckets[index];
Node currentNode = previousNode.next;
while (currentNode != null) {
if (currentNode.key == key) {
currentNode.value = value;
return;
}
previousNode = currentNode;
currentNode = currentNode.next;
}
previousNode.next = new Node(key, value);
}
public int get(int key) {
int index = getHash(key);
if (buckets[index] == null) {
return -1;
}
Node currentNode = buckets[index].next;
while (currentNode != null ){
if (currentNode.key == key) {
return currentNode.value;
}
currentNode = currentNode.next;
}
return -1;
}
public void remove(int key) {
int index = getHash(key);
if (buckets[index] == null) {
return;
}
Node previousNode = buckets[index];
Node currentNode = previousNode.next;
while (currentNode != null) {
if (currentNode.key == key) {
previousNode.next = currentNode.next;
return;
}
previousNode = currentNode;
currentNode = currentNode.next;
}
}
}