forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyHashMap.java
105 lines (90 loc) · 2.57 KB
/
MyHashMap.java
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.leetcode.hashtables;
/**
* Level: Learning cards
* Problem Link: https://leetcode.com/explore/learn/card/hash-table/182/practical-applications/1140/
* Runtime: https://leetcode.com/submissions/detail/224928756/
*
* @author rampatra
* @since 2019-04-25
*/
public class MyHashMap {
class Entry {
int key;
int value;
Entry next;
Entry(int key, int value) {
this.key = key;
this.value = value;
}
}
private final int SIZE = 10000;
private final Entry[] entries;
/**
* Initialize your data structure here.
*/
public MyHashMap() {
entries = new Entry[SIZE];
}
/**
* value will always be non-negative.
*/
public void put(int key, int value) {
int bucket = key % SIZE;
Entry entry = entries[bucket];
if (entry == null) {
entries[bucket] = new Entry(key, value);
} else {
while (entry.next != null && entry.key != key) {
entry = entry.next;
}
if (entry.key == key) {
entry.value = value;
} else {
entry.next = new Entry(key, 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 = key % SIZE;
Entry entry = entries[bucket];
while (entry != null) {
if (entry.key == key) {
return entry.value;
}
entry = entry.next;
}
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 = key % SIZE;
Entry entry = entries[bucket];
if (entry != null && entry.key == key) {
entries[bucket] = entry.next;
return;
}
Entry curr = new Entry(0, 0);
curr.next = entry;
while (curr.next != null && curr.next.key != key) {
curr = curr.next;
}
if (curr.next != null) {
curr.next = curr.next.next;
}
}
public static void main(String[] args) {
MyHashMap map = new MyHashMap();
map.put(1, 2);
System.out.println("1 -> " + map.get(1));
map.put(1, 4);
System.out.println("1 -> " + map.get(1));
map.remove(1);
System.out.println("1 -> " + map.get(1));
System.out.println("5 -> " + map.get(5));
}
}