Leetcode 981 基于时间的键值存储 红黑树与二分查找
JAVA 实现,基于红黑树:
class TimeMap { Map<String, TreeMap<Integer, String>> map = new HashMap<String, TreeMap<Integer, String>>(); /** * Initialize your data structure here. */ public TimeMap() { } public void set(String key, String value, int timestamp) { if (!map.containsKey(key)) map.put(key, new TreeMap<Integer, String>()); map.get(key).put(timestamp, value); } public String get(String key, int timestamp) { if (!map.containsKey(key)) return ""; TreeMap<Integer, String> tree = map.get(key); Integer searchKey = tree.floorKey(timestamp); return searchKey == null ? "" : tree.get(searchKey); } }
JS 实现,基于二分查找:
/** * Initialize your data structure here. */ var TimeMap = function () { this.map = new Map(); }; /** * @param {string} key * @param {string} value * @param {number} timestamp * @return {void} */ TimeMap.prototype.set = function (key, value, timestamp) { if (!this.map.has(key)) this.map.set(key, []); let timeElements = this.map.get(key); timeElements.push(new TimeElement(timestamp, value)); }; /** * @param {string} key * @param {number} timestamp * @return {string} */ TimeMap.prototype.get = function (key, timestamp) { if (!this.map.has(key)) return ""; let timeElements = this.map.get(key), len = timeElements.length, leftPoint = 0, rightPoint = len - 1; while (leftPoint < rightPoint - 1) { let mid = Math.floor((leftPoint + rightPoint) / 2); if (timeElements[mid].timestamp < timestamp) leftPoint = mid; else rightPoint = mid; } let re = leftPoint + 1 < len && timeElements[leftPoint + 1].timestamp <= timestamp ? timeElements[leftPoint + 1] : timeElements[leftPoint]; return re.timestamp <= timestamp ? re.value : ""; }; var TimeElement = function (timestap, value) { this.timestamp = timestap; this.value = value; } /** * Your TimeMap object will be instantiated and called as such: * var obj = new TimeMap() * obj.set(key,value,timestamp) * var param_2 = obj.get(key,timestamp) */
当你看清人们的真相,于是你知道了,你可以忍受孤独
分类:
数据结构与算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构