-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathMyHashMap.java
More file actions
78 lines (53 loc) · 1.71 KB
/
MyHashMap.java
File metadata and controls
78 lines (53 loc) · 1.71 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
import java.util.*;
class MyHashMap {
int primaryBucket;
int secondaryBucket;
int[][] storage;
public MyHashMap() {
this.primaryBucket = 1000;
this.secondaryBucket = 1000;
this.storage = new int[primaryBucket +1][];
}
public int getPrimaryHash(int key) {
return key / primaryBucket;
}
public int getSecondaryHash(int key) {
return key % secondaryBucket;
}
public void put(int key, int value) {
int primaryIndex = getPrimaryHash(key);
if (storage[primaryIndex] == null) {
if (primaryIndex == 0) {
storage[primaryIndex] = new int[secondaryBucket + 1];
} else {
storage[primaryIndex] = new int[secondaryBucket];
}
Arrays.fill(storage[primaryIndex], -1);
}
int secondaryIndex = getSecondaryHash(key);
storage[primaryIndex][secondaryIndex] = value;
}
public int get(int key) {
int primaryIndex = getPrimaryHash(key);
if (storage[primaryIndex] == null)
return -1;
int secondaryIndex = getSecondaryHash(key);
return storage[primaryIndex][secondaryIndex];
}
public void remove(int key) {
int primaryIndex = getPrimaryHash(key);
if (storage[primaryIndex] == null)
return;
int secondaryIndex = getSecondaryHash(key);
storage[primaryIndex][secondaryIndex] = -1;
}
}
// TC - O(1)
// SC - O(10^6) //As it is demmand on allocation so actual is O(1)
/**
* 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);
*/