-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesignHashMap.java
More file actions
89 lines (75 loc) · 2.18 KB
/
Copy pathDesignHashMap.java
File metadata and controls
89 lines (75 loc) · 2.18 KB
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
class MyHashMap {
private final LinkedList[] data;
private static final int N = 10;
/** Initialize your data structure here. */
public MyHashMap() {
data = new LinkedList[N];
for(int i = 0; i < N; i++) {
data[i] = new LinkedList();
}
}
/** value will always be non-negative. */
public void put(int key, int value) {
data[key%N].add(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) {
return data[key%N].get(key);
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
data[key%N].remove(key);
}
private static class LinkedList {
static class Node {
int key;
int val;
Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
private final Node dummy = new Node(0, 0);
void add(int k, int v) {
Node p = dummy.next;
while (p != null) {
if (p.key == k) {
p.val = v;
break;
}
p = p.next;
}
if (p == null) {
Node node = new Node(k, v);
node.next = dummy.next;
dummy.next = node;
}
}
void remove(int k) {
Node p = dummy;
while (p.next != null) {
if (p.next.key == k) {
p.next = p.next.next;
return;
}
p = p.next;
}
}
int get(int k) {
Node p = dummy.next;
while (p != null) {
if (p.key == k) return p.val;
p = p.next;
}
return -1;
}
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/