forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashMap.java
More file actions
81 lines (74 loc) · 2.05 KB
/
Copy pathMyHashMap.java
File metadata and controls
81 lines (74 loc) · 2.05 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
// Time Complexity : Amortized time complexity for operations - put, get, remove is O(1).
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
class MyHashMap {
class Node{
int key;
int value;
Node next;
public Node(int key, int value){
this.key = key;
this.value = value;
}
}
private Node [] storage;
private int hash(int key){
return key % 10000;
}
public MyHashMap() {
this.storage = new Node[10000];
}
private Node find(Node head, int key){
Node previous = head;
Node current = head.next;
while(current!=null && current.key != key){
previous = current;
current = current.next;
}
return previous;
}
public void put(int key, int value) {
int itemIndex = hash(key);
if(storage[itemIndex] == null){
storage[itemIndex] = new Node(-1,-1);
}
Node previous = find(storage[itemIndex], key);
if(previous.next == null){
previous.next = new Node(key, value);
} else{
previous.next.value = value;
}
}
public int get(int key) {
int itemIndex = hash(key);
if(storage[itemIndex] == null){
return -1;
}
Node previous = find(storage[itemIndex], key);
if(previous.next == null){
return -1;
}
return previous.next.value;
}
public void remove(int key) {
int itemIndex = hash(key);
if(storage[itemIndex] == null){
return;
}
Node previous = find(storage[itemIndex], key);
if(previous.next == null){
return;
}
Node temp = previous.next;
previous.next = temp.next;
temp.next = null;
}
}
/**
* 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);
*/