forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashMap.java
More file actions
72 lines (59 loc) · 1.88 KB
/
MyHashMap.java
File metadata and controls
72 lines (59 loc) · 1.88 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
/*
Time complexity : put : O(1)
remove O(1)
get O(1)
Space Complexity : O(N) N = input size
Is worked on leetcode : YES
*/
class MyHashMap {
Integer [][] storage;
int buckets;
int bucket_items;
/** Initialize your data structure here. */
public MyHashMap() {
buckets =1001;
bucket_items=1000;
storage = new Integer[buckets][];
}
private int bucket(int key){
return key % buckets;
}
private int bucket_item (int key){
return key / bucket_items;
}
/** value will always be non-negative. */
public void put(int key, int value) {
int bucket_no = bucket(key);
int bucket_item_no = bucket_item(key);
if(storage[bucket_no] == null){
storage[bucket_no] = new Integer[bucket_items];
}
storage[bucket_no][bucket_item_no] = value;
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
int bucket_no = bucket(key);
int bucket_item_no = bucket_item(key);
if(storage[bucket_no] != null){
if(storage[bucket_no][bucket_item_no] == null){
return -1;
}else{
return storage[bucket_no][bucket_item_no];
}
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
int bucket_no = bucket(key);
int bucket_item_no = bucket_item(key);
if(storage[bucket_no] != null){
storage[bucket_no][bucket_item_no] = null;
}
}
public static void main(String[] args) {
MyHashMap hm = new MyHashMap();
hm.put(1, 1);
hm.get(1);
}
}