forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution2.java
More file actions
106 lines (85 loc) · 2.65 KB
/
Copy pathsolution2.java
File metadata and controls
106 lines (85 loc) · 2.65 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Time Complexity :
// put(key, value) -> Average: O(1), Worst: O(n) (if many keys fall in same bucket)
// get(key) -> Average: O(1), Worst: O(n)
// remove(key) -> Average: O(1), Worst: O(n)
// (n = number of nodes in that bucket)
//
// Space Complexity :
// O(N + B) where N = total pairs stored, B = number of buckets
//
// Did this code successfully run on Leetcode :
// Yes
//
// Any problem you faced while coding this :
// No major issues. Just need to handle collisions using a LinkedList,
// and update value if key already exists.
// Your code here along with comments explaining your approach
import java.util.LinkedList;
class MyHashMap {
// total buckets size
int parentbuckets;
// each index has a linkedlist of nodes (to handle collisions)
LinkedList<Node>[] storage;
// simple node class to store key-value
static class Node {
int key;
int value;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
public MyHashMap() {
this.parentbuckets = 1000;
storage = new LinkedList[parentbuckets];
}
// hash function to find bucket index
private int getPrimaryHash(int key) {
return Math.floorMod(key, parentbuckets);
}
public void put(int key, int value) {
int index = getPrimaryHash(key);
// if bucket not created, create it
if (storage[index] == null) {
storage[index] = new LinkedList<>();
}
// check if key already exists -> update
for (Node n : storage[index]) {
if (n.key == key) {
n.value = value;
return;
}
}
// if key not found, add new node
storage[index].add(new Node(key, value));
}
public int get(int key) {
int index = getPrimaryHash(key);
// if bucket empty, key not present
if (storage[index] == null) return -1;
// search in that bucket
for (Node n : storage[index]) {
if (n.key == key) return n.value;
}
return -1;
}
public void remove(int key) {
int index = getPrimaryHash(key);
// if bucket doesn't exist, nothing to remove
if (storage[index] == null) return;
// find and remove the node
for (Node n : storage[index]) {
if (n.key == key) {
storage[index].remove(n);
break;
}
}
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/