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
67 lines (54 loc) · 1.83 KB
/
MyHashMap.java
File metadata and controls
67 lines (54 loc) · 1.83 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
// Time Complexity : O(1)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode :Yes
// Any problem you faced while coding this : No
// Approach:
// Use two-level indexing with primary and secondary hashing.
// Store values in a 2D array and use -1 to represent missing keys.
class MyHashMap {
int primaryBuckets;
int secondaryBuckets;
int[][] storage;
public MyHashMap() {
this.primaryBuckets = 1000;
this.secondaryBuckets = 1000;
this.storage = new int[primaryBuckets][];
}
private int getPrimaryHash(int key) {
return key % primaryBuckets;
}
private int getSecondaryHash(int key) {
return key / secondaryBuckets;
}
public void put(int key, int value) {
int primaryIndex = getPrimaryHash(key);
if (storage[primaryIndex] == null) {
if (primaryIndex == 0) {
storage[primaryIndex] = new int[secondaryBuckets + 1];
} else {
storage[primaryIndex] = new int[secondaryBuckets];
}
for (int i = 0; i < storage[primaryIndex].length; i++) {
storage[primaryIndex][i] = -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;
}
}