-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path706. Design HashMap.java
More file actions
58 lines (49 loc) · 1.33 KB
/
Copy path706. Design HashMap.java
File metadata and controls
58 lines (49 loc) · 1.33 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
class Element{
private int key,val;
Element(){
}
Element(int key,int val){
this.key=key;
this.val=val;
}
public int getKey() {
return key;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
class MyHashMap {
private int prime = 3499;
private List<LinkedList<Element>> list;
private int hashFunction(int x){
return x%prime;
}
public MyHashMap() {
list = new ArrayList<LinkedList<Element>>(Collections.nCopies(prime, new LinkedList<Element>()));
}
private Element getElement(int key){
LinkedList<Element> linkedList = list.get(hashFunction(key));
for(Element e : linkedList) if(key==e.getKey()) return e;
return null;
}
/** value will always be non-negative. */
public void put(int key, int value) {
Element e = getElement(key);
if(e==null) list.get(hashFunction(key)).add(new Element(key,value));
else e.setVal(value);
}
public int get(int key) {
Element e = getElement(key);
if(e==null) return -1;
else return e.getVal();
}
public void remove(int key) {
Element e = getElement(key);
if(e==null) return;
else list.get(hashFunction(key)).remove(e);
}
}