-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathMyHashMap.java
More file actions
79 lines (63 loc) · 1.68 KB
/
MyHashMap.java
File metadata and controls
79 lines (63 loc) · 1.68 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
// Time Complexity : O(1) average
// Space Complexity :O(n + 10000)
// 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
class MyHashMap {
class Node{
int key, val;
Node next;
public Node(int key, int val){
this.key = key;
this.val = val;
}
}
private Node[] storage;
public MyHashMap() {
this.storage = new Node[10000];
}
public int hash(int key){
return key%10000;
}
public Node find(Node head, int key){
Node prev = null;
Node curr = head;
while(curr != null && curr.key != key){
prev = curr;
curr = curr.next;
}
return prev;
}
public void put(int key, int value) {
int idx = hash(key);
if(storage [idx] == null){
storage[idx] = new Node(-1,-1);
}
Node prev = find(storage[idx], key);
if(prev.next !=null){
prev.next.val = value;
}else{
prev.next = new Node(key,value);
}
}
public int get(int key) {
int idx = hash(key);
if(storage[idx] == null) return -1;
Node prev = find(storage[idx], key);
if(prev.next !=null){
return prev.next.val;
}
return -1;
}
public void remove(int key) {
int idx = hash(key);
if(storage[idx] == null){
return;
}
Node prev = find(storage[idx], key);
if(prev.next == null){
return;
}
prev.next = prev.next.next;
}
}