1
+ import javafx .util .*;
2
+ class MyHashMap {
3
+ private final int SIZE = 100000 ;
4
+ private List <Pair <Integer , Integer >> bucket [];
5
+
6
+ /** Initialize your data structure here. */
7
+ public MyHashMap () {
8
+ bucket = new ArrayList [SIZE ];
9
+ }
10
+
11
+ private int hash (int key ){
12
+ return key % SIZE ;
13
+ }
14
+
15
+ private int getPos (int key , int index ){
16
+ List <Pair <Integer , Integer >> temp = bucket [index ];
17
+ if (temp == null ) return -1 ;
18
+ for (int i = 0 ; i < temp .size (); i ++){
19
+ if (temp .get (i ).getKey () == key )
20
+ return i ;
21
+ }
22
+ return -1 ;
23
+ }
24
+ /** value will always be non-negative. */
25
+ public void put (int key , int value ) {
26
+ int index = hash (key );
27
+ int pos = getPos (key , index );
28
+ if (pos < 0 ){
29
+ if (bucket [index ] == null )
30
+ bucket [index ] = new ArrayList <Pair <Integer , Integer >>();
31
+
32
+ Pair <Integer , Integer > pair = new Pair <Integer , Integer >(key , value );
33
+ bucket [index ].add (pair );
34
+ }
35
+ else {
36
+ bucket [index ].set (pos , new Pair <Integer , Integer >(key , value ));
37
+ }
38
+ }
39
+
40
+ /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
41
+ public int get (int key ) {
42
+ int index = hash (key );
43
+ int pos = getPos (key , index );
44
+ if (pos < 0 ) return -1 ;
45
+ else {
46
+ return bucket [index ].get (pos ).getValue ();
47
+ }
48
+ }
49
+
50
+ /** Removes the mapping of the specified value key if this map contains a mapping for the key */
51
+ public void remove (int key ) {
52
+ int index = hash (key );
53
+ int pos = getPos (key , index );
54
+ if (pos < 0 ) return ;
55
+ else {
56
+ bucket [index ].remove (pos );
57
+ }
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Your MyHashMap object will be instantiated and called as such:
63
+ * MyHashMap obj = new MyHashMap();
64
+ * obj.put(key,value);
65
+ * int param_2 = obj.get(key);
66
+ * obj.remove(key);
67
+ */
0 commit comments