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)
 */
复制代码

 

posted @   牛有肉  阅读(281)  评论(0编辑  收藏  举报
编辑推荐:
· 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语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示