0%

算法-哈希表

哈希表相关算法题

设计有setAll功能的哈希表,put、get、setAll方法,时间复杂度O(1)

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
/**
* 带有时间戳的值
* @param <V>
*/
public static class MyValue<V> {
public V value;
public long time;

public MyValue(V v, long t) {
value = v;
time = t;
}
}

public static class MyHashMap<K, V> {
private final HashMap<K, MyValue<V>> map;
private long time;
/**
* 保持setAll的值
*/
private MyValue<V> setAll;

public MyHashMap() {
this.map = new HashMap<>();
time = 0;
setAll = new MyValue<>(null, -1);
}

public void put(K key, V value) {
map.put(key, new MyValue<>(value, time++));
}

public void setAll(V value) {
setAll = new MyValue<>(value, time++);
}

public V get(K key) {
if (!map.containsKey(key)) {
return null;
}
// 比较map与setAll的时间,时间大的覆盖时间小的
if (map.get(key).time > setAll.time) {
return map.get(key).value;
}
return setAll.value;
}

}