哈希表相关算法题
设计有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
|
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;
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; } if (map.get(key).time > setAll.time) { return map.get(key).value; } return setAll.value; }
}
|