【简单】设计有setAll功能的哈希表-Java
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请轻击人工智能教程大家好!欢迎来到我的网站! 人工智能被认为是一种拯救世界、终结世界的技术。毋庸置疑,人工智能时代就要来临了,科… 继续阅读 前言https://www.captainai.net/troubleshooter
package live.every.day.ProgrammingDesign.CodingInterviewGuide.Other; import java.util.HashMap; /** * 设计有setAll功能的哈希表 * * 【题目】 * 哈希表常见的三个操作是put、get和containsKey,而且这三个操作的时间复杂度为O(1)。现在想加一个setAll功能,就是把所 * 有记录的value都设成统一的值。请设计并实现这种有setAll功能的哈希表,并且put、get、containsKey和setAll四个操作的 * 时间复杂度都为O(1)。 * * 【难度】 * 简单 * * 【解答】 * 加入一个时间戳结构,一切问题就变得非常简单了。具体步骤如下: * 1.把每一个记录都加上一个时间,标记每条记录是何时建立的。 * 2.设置一个setAll记录也加上一个时间,标记setAll记录建立的时间。 * 3.查询记录时,如果某条记录的时间早于setAll记录的时间,说明setAll是最新数据,返回setAll记录的值。如果某条记录的时间 * 晚于setAll记录的时间,说明记录的值是最新数组,返回该条记录的值。 * 具体请参看如下的SetAllHashMap类。 * * @author Created by LiveEveryDay */ public class SetAllHashMap<K, V> { public static class MyValue<V> { private final V value; private final 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; } } private final HashMap<K, MyValue<V>> baseMap; private long time; private MyValue<V> setAll; public SetAllHashMap() { this.baseMap = new HashMap<>(); this.time = 0; this.setAll = new MyValue<>(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<>(value, this.time++)); } public void setAll(V value) { this.setAll = new MyValue<>(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; } } public static void main(String[] args) { SetAllHashMap<String, Integer> map = new SetAllHashMap<>(); map.put("key", 1); map.setAll(0); System.out.printf("The result is: %d", map.get("key")); } } // ------ Output ------ /* The result is: 0 */