@@ -68,13 +68,99 @@ class ListNode {
68
68
}
69
69
}
70
70
}
71
+ }
72
+
73
+ public static class Solution2 {
74
+
75
+ public static class MyHashMap {
76
+ /**
77
+ * Considering the given constraints for this problem on LeetCode, load factors and resizing/rehashing are not considered. Thus an EASY problem.
78
+ * <p>
79
+ * inspired by: https://leetcode.com/problems/design-hashmap/discuss/225312/hashmaparraylinkedlistcollision
80
+ */
81
+ class Node {
82
+ /**
83
+ * We need to have both key and val in this ListNode because all values input key are hashed to the same bucket, so we need its original key
84
+ * to be a differentiator within this bucket.
85
+ */
86
+ int val ;
87
+ int key ;
88
+ Node next ;
89
+
90
+ public Node (int key , int val ) {
91
+ this .key = key ;
92
+ this .val = val ;
93
+ }
94
+ }
95
+
96
+ Node [] nodes ;
97
+ int SIZE = 1000000 ;
98
+
99
+ /**
100
+ * Initialize your data structure here.
101
+ */
102
+ public MyHashMap () {
103
+ nodes = new Node [SIZE ];
104
+ }
105
+
106
+ /**
107
+ * value will always be non-negative.
108
+ */
109
+ public void put (int key , int value ) {
110
+ int index = getHashedKey (key );
111
+ Node head = nodes [index ];
112
+ Node tmp = head ;
113
+ while (tmp != null ) {
114
+ if (tmp .key == key ) {
115
+ tmp .val = value ;
116
+ return ;
117
+ }
118
+ tmp = tmp .next ;
119
+ }
120
+ Node newHead = new Node (key , value );
121
+ newHead .next = head ;
122
+ nodes [index ] = newHead ;
123
+ }
124
+
125
+ private int getHashedKey (int key ) {
126
+ return Integer .hashCode (key ) % SIZE ;
127
+ }
71
128
72
- /**
73
- * Your MyHashMap object will be instantiated and called as such:
74
- * MyHashMap obj = new MyHashMap();
75
- * obj.put(key,value);
76
- * int param_2 = obj.get(key);
77
- * obj.remove(key);
78
- */
129
+ /**
130
+ * Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
131
+ */
132
+ public int get (int key ) {
133
+ Node head = nodes [getHashedKey (key )];
134
+ Node tmp = head ;
135
+ while (tmp != null && tmp .key != key ) {
136
+ tmp = tmp .next ;
137
+ }
138
+ if (tmp == null ) {
139
+ return -1 ;
140
+ }
141
+ if (tmp .key == key ) {
142
+ return tmp .val ;
143
+ }
144
+ return -1 ;
145
+ }
146
+
147
+ /**
148
+ * Removes the mapping of the specified value key if this map contains a mapping for the key
149
+ */
150
+ public void remove (int key ) {
151
+ /**We can just set the value of this key to -1 since the constraint for this problem is that all values are >= 0*/
152
+ Node node = nodes [getHashedKey (key )];
153
+ Node tmp = node ;
154
+ Node pre = new Node (-1 , -1 );
155
+ pre .next = tmp ;
156
+ while (tmp != null ) {
157
+ if (tmp .key == key ) {
158
+ tmp .val = -1 ;
159
+ return ;
160
+ }
161
+ tmp = tmp .next ;
162
+ }
163
+ }
164
+ }
79
165
}
80
166
}
0 commit comments