最近一段时间太忙了,导致即使刷过的题也没能计时放在博客上!
一定要每天都写都记录!
题目
哈希表常见的三个操作时put、get和containsKey,而且这三个操作的时间复杂度为O(1)。现在想加一个setAll功能,就是把所有记录的value值设成统一的值。请设计并实现这种有setAll功能的哈希表,并且put、get、containsKey和setAll四个操作的时间复杂度都为O(1)。
问题分析
加入一个时间戳结构,具体步骤如下:
1.把每一个记录都加上一个时间,标记每条记录是何时建立的。
2.设置一个setAll记录也加上一个时间,标记setAll记录建立的时间。
3.查询记录时,如果是某条记录的时间早于setAll记录的时间,说明setAll是最新数据,返回setAll记录的值。如果某条记录的时间晚于setAll记录的时间,说明记录的值是最新的数据,返回该条记录的值。
JAVA代码实现
package otherquestions;
public class MyValue<V> {
private V value;
private long time;
public MyValue(V value, long time) {
this.value = value;
this.time = time;
}
public V getValue() {
return this.value;
}
public long getTime() {
return this.time;
}
}
package otherquestions;
import java.util.HashMap;
public class MyHashMap1212<K, V> {
private HashMap<K, MyValue<V>> baseMap;
private long time;
private MyValue<V> setAll;
public MyHashMap1212() {
this.baseMap = new HashMap<>();
this.time = 0;
this.setAll = new MyValue<V>(null, -1);
}
public boolean containsKey(K key) {
return this.baseMap.containsKey(key);
}
public void put(K key, V value) {
this.baseMap.put(key, new MyValue<V>(value, this.time++));
}
public void setAll(V value) {
this.setAll = new MyValue<V>(value, this.time++);
}
public V get(K key) {
if (this.containsKey(key)) {
if (this.baseMap.get(key).getTime() > this.setAll.getTime()) {
return this.baseMap.get(key).getValue();
} else {
return this.setAll.getValue();
}
} else {
return null;
}
}
}