-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ706DesignHashMap.java
More file actions
82 lines (71 loc) · 1.84 KB
/
Q706DesignHashMap.java
File metadata and controls
82 lines (71 loc) · 1.84 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
/*
@b-knd (jingru) on 31 July 2022 03:16:00
*/
//Improved and faster implementation
class MyHashMap {
int[] data;
int size;
//O(1)
public MyHashMap() {
data = new int[1];
size = 1;
data[0] = -1;
}
//O(N) on worst case if resizing is needed, O(1) on best case
public void put(int key, int value) {
if(key >= size){
int[] newArr = new int[size + key + 1];
Arrays.fill(newArr, -1);
System.arraycopy(data, 0, newArr, 0, size);
data = newArr;
size = data.length;
}
data[key] = value;
}
//O(1) time
public int get(int key) {
if(key >= size){
return -1;
}
return data[key];
}
//O(1) time
public void remove(int key) {
if(key < size){
data[key] = -1;
}
}
}
/*----------------------------------------------------------------------------------------------------------------*/
// My implementation
// most of the function requires using the method indexOf which gives O(N) time complexity
class MyHashMap {
ArrayList<Integer> keys, values;
public MyHashMap() {
keys = new ArrayList<>();
values = new ArrayList<>();
}
public void put(int key, int value) {
if(keys.contains(key)){
int i = keys.indexOf(key);
values.set(i, value);
} else{
keys.add(key);
values.add(value);
}
}
public int get(int key) {
if(keys.contains(key)){
return values.get(keys.indexOf(key));
} else{
return -1;
}
}
public void remove(int key) {
if(keys.contains(key)){
int i = keys.indexOf(key);
keys.remove(i);
values.remove(i);
}
}
}