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 (72 loc) · 2.3 KB
/
Copy pathMyHashMap.java
File metadata and controls
81 lines (72 loc) · 2.3 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 : O(1)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
public class MyHashMap {
class Node {
int key;
int value;
Node next;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
int bucketSize;
Node[] buckets;
public MyHashMap() {
bucketSize = 9999;
buckets = new Node[bucketSize];
}
public int getHash(int key) {
return key % bucketSize;
}
public Node getPrev(Node node, int key) {
Node prev = node;
while(prev.next != null && prev.next.key != key) {
prev = prev.next;
}
return prev;
}
public void put(int key, int value) {
int hash = getHash(key);
Node node = new Node(key,value);
if(buckets[hash] == null) {
buckets[hash] = new Node(-1,-1);
buckets[hash].next = node;
}
else {
Node previousNode = getPrev(buckets[hash], key);
if(previousNode.next != null) {
previousNode.next.value = value;
} else {
previousNode.next = node;
}
}
}
public int get(int key) {
int hash = getHash(key);
if(buckets[hash] == null) {
return -1;
}
else if(buckets[hash] != null) {
Node previousNode = getPrev(buckets[hash], key);
if(previousNode != null && previousNode.next != null) {
return previousNode.next.value;
}
}
return -1;
}
public void remove(int key) {
int hash = getHash(key);
if(buckets[hash] == null) {
return;
}
else {
Node previousNode = getPrev(buckets[hash], key);
if(previousNode != null && previousNode.next != null) {
previousNode.next = previousNode.next.next;
}
}
}
}