1+ package com .leetcode .hashtables ;
2+
3+ /**
4+ * Level: Learning cards
5+ * Problem Link: https://leetcode.com/explore/learn/card/hash-table/182/practical-applications/1140/
6+ * Runtime: https://leetcode.com/submissions/detail/224928756/
7+ *
8+ * @author rampatra
9+ * @since 2019-04-25
10+ */
11+ public class MyHashMap {
12+
13+ class Entry {
14+ int key ;
15+ int value ;
16+ Entry next ;
17+
18+ Entry (int key , int value ) {
19+ this .key = key ;
20+ this .value = value ;
21+ }
22+ }
23+
24+ private final int SIZE = 10000 ;
25+ private final Entry [] entries ;
26+
27+ /**
28+ * Initialize your data structure here.
29+ */
30+ public MyHashMap () {
31+ entries = new Entry [SIZE ];
32+ }
33+
34+ /**
35+ * value will always be non-negative.
36+ */
37+ public void put (int key , int value ) {
38+ int bucket = key % SIZE ;
39+ Entry entry = entries [bucket ];
40+
41+ if (entry == null ) {
42+ entries [bucket ] = new Entry (key , value );
43+ } else {
44+ while (entry .next != null && entry .key != key ) {
45+ entry = entry .next ;
46+ }
47+
48+ if (entry .key == key ) {
49+ entry .value = value ;
50+ } else {
51+ entry .next = new Entry (key , value );
52+ }
53+ }
54+ }
55+
56+ /**
57+ * Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
58+ */
59+ public int get (int key ) {
60+ int bucket = key % SIZE ;
61+ Entry entry = entries [bucket ];
62+ while (entry != null ) {
63+ if (entry .key == key ) {
64+ return entry .value ;
65+ }
66+ entry = entry .next ;
67+ }
68+ return -1 ;
69+ }
70+
71+ /**
72+ * Removes the mapping of the specified value key if this map contains a mapping for the key
73+ */
74+ public void remove (int key ) {
75+ int bucket = key % SIZE ;
76+ Entry entry = entries [bucket ];
77+
78+ if (entry != null && entry .key == key ) {
79+ entries [bucket ] = entry .next ;
80+ return ;
81+ }
82+
83+ Entry curr = new Entry (0 , 0 );
84+ curr .next = entry ;
85+
86+ while (curr .next != null && curr .next .key != key ) {
87+ curr = curr .next ;
88+ }
89+
90+ if (curr .next != null ) {
91+ curr .next = curr .next .next ;
92+ }
93+ }
94+
95+ public static void main (String [] args ) {
96+ MyHashMap map = new MyHashMap ();
97+ map .put (1 , 2 );
98+ System .out .println ("1 -> " + map .get (1 ));
99+ map .put (1 , 4 );
100+ System .out .println ("1 -> " + map .get (1 ));
101+ map .remove (1 );
102+ System .out .println ("1 -> " + map .get (1 ));
103+ System .out .println ("5 -> " + map .get (5 ));
104+ }
105+ }
0 commit comments