-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign-hashmap.java
103 lines (85 loc) · 1.86 KB
/
design-hashmap.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
class MyHashMap {
private final int size = 13;
Entry[] buckets;
/** Initialize your data structure here. */
public MyHashMap() {
this.buckets = new Entry[size];
}
/** value will always be non-negative. */
public void put(int key, int value) {
int i = getIndex(key);
Entry curr = buckets[i];
if (curr == null) {
buckets[i] = new Entry(key, value);
return;
}
while (curr.next != null) {
if (curr.key == key) {
curr.value = value;
return;
}
curr = curr.next;
}
if (curr.key == key) {
curr.value = value;
} else {
curr.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 i = getIndex(key);
Entry curr = buckets[i];
if (curr == null) {
return -1;
}
while (curr != null) {
if (curr.key == key) {
return curr.value;
}
curr = curr.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 i = getIndex(key);
Entry curr = buckets[i];
Entry prev = null;
if (curr == null) {
return;
}
while (curr != null) {
if (curr.key == key) {
if (prev == null) {
buckets[i] = curr.next;
} else {
Entry next = curr.next;
prev.next = next;
curr.next = null;
}
return;
}
prev = curr;
curr = curr.next;
}
}
private int getIndex(int key) {
return Math.abs(key * 12582917 % size);
}
private class Entry {
int key;
int value;
Entry next;
public Entry(int key, int value) {
this.key = key;
this.value = value;
}
}
}