-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashMap.java
88 lines (72 loc) · 1.96 KB
/
HashMap.java
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
// Implement HashMap using Arrays in Java. It handles collisions too using chaining
class ListNode {
int key;
int val;
ListNode next;
ListNode (int key, int val, ListNode next) {
this.key = key;
this.val = val;
this.next = next;
}
}
class MyHashMap {
private final int SIZE = 1000;
ListNode[] buckets;
public MyHashMap() {
buckets = new ListNode[SIZE];
}
private int hash(int key) {
return key % SIZE;
}
public void put(int key, int value) {
remove(key); //remove if already present
int index = hash(key);
if (buckets[index] == null)
buckets[index] = new ListNode(key, value, null);
else {
ListNode curr = buckets[index];
while (curr.next != null)
curr = curr.next;
curr.next = new ListNode(key, value, null);
}
}
public int get(int key) {
int index = hash(key);
ListNode curr = buckets[index];
while (curr != null) {
if (curr.key == key)
return curr.val;
curr = curr.next;
}
return -1; //not found
}
public void remove(int key) {
int index = hash(key);
if (buckets[index] == null)
return;
if (buckets[index].key == key) {
buckets[index] = buckets[index].next;
return;
}
ListNode prev = buckets[index];
ListNode curr = prev.next;
while (curr != null) {
if (curr.key == key) {
prev.next = curr.next;
return;
}
prev = curr;
curr = curr.next;
}
return;
}
}
public class HashMap {
public static void main(String[] args) {
MyHashMap map = new MyHashMap();
map.put(1, 10);
map.put(3, 15);
map.put(2, 5);
System.out.println(map.get(3));
}
}