-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathMyHashMap.java
More file actions
64 lines (51 loc) · 2.02 KB
/
Copy pathMyHashMap.java
File metadata and controls
64 lines (51 loc) · 2.02 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
// Time Complexity : put: O(1), get: O(1), remove: O(1)
// Space Complexity : O(10^6)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
//Description:
// - Uses a 2D array as a hash table with two-level hashing.
// - The first hash selects a primary bucket, and the second hash selects an index within that bucket.
// - Buckets are created only when needed, allowing direct access to values in constant time.
class MyHashMap {
private static final int PRIMARY_BUCKET_SIZE = 1000;
private static final int SECONDARY_BUCKET_SIZE = 1000;
private final int[][] primaryBuckets;
public MyHashMap() {
this.primaryBuckets = new int[PRIMARY_BUCKET_SIZE][];
}
public void put(int key, int value) {
int primaryHash = getPrimaryHash(key);
if(this.primaryBuckets[primaryHash] == null) {
int secondaryBucketSize = SECONDARY_BUCKET_SIZE;
if(primaryHash == 0) {
secondaryBucketSize += 1;
}
this.primaryBuckets[primaryHash] = new int[secondaryBucketSize];
Arrays.fill(this.primaryBuckets[primaryHash], -1);
}
int secondaryHash = getSecondaryHash(key);
this.primaryBuckets[primaryHash][secondaryHash] = value;
}
public int get(int key) {
int primaryHash = getPrimaryHash(key);
if(this.primaryBuckets[primaryHash] == null) {
return -1;
}
int secondaryHash = getSecondaryHash(key);
return this.primaryBuckets[primaryHash][secondaryHash];
}
public void remove(int key) {
int primaryHash = getPrimaryHash(key);
if(this.primaryBuckets[primaryHash] == null) {
return;
}
int secondaryHash = getSecondaryHash(key);
this.primaryBuckets[primaryHash][secondaryHash] = -1;
}
private int getPrimaryHash(int key) {
return key % PRIMARY_BUCKET_SIZE;
}
private int getSecondaryHash(int key) {
return key / SECONDARY_BUCKET_SIZE;
}
}