作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/time-based-key-value-store/

题目描述

Create a timebased key-value store class TimeMap, that supports two operations.

  1. set(string key, string value, int timestamp)
  • Stores the key and value, along with the given timestamp.
  1. get(string key, int timestamp)
  • Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.
  • If there are multiple such values, it returns the one with the largest timestamp_prev.
  • If there are no values, it returns the empty string ("").

Example 1:

Input: inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,"bar","bar",null,"bar2","bar2"]
Explanation:
TimeMap kv;
kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1
kv.get("foo", 1); // output "bar"
kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"
kv.set("foo", "bar2", 4);
kv.get("foo", 4); // output "bar2"
kv.get("foo", 5); //output "bar2"

Example 2:

Input: inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
Output: [null,null,null,"","high","high","low","low"]

Note:

  1. All key/value strings are lowercase.
  2. All key/value strings have length in the range [1, 100]
  3. The timestamps for all TimeMap.set operations are strictly increasing.
  4. 1 <= timestamp <= 10^7
  5. TimeMap.set and TimeMap.get functions will be called a total of 120000 times (combined) per test case.

题目大意

构建一个带有时间版本的KV存储器。即每次保存的时候会保存当前的时间,查询的时候给出一个时间,要求找到先于该时间的最新的key对应的value。

解题方法

字典

没想到LC还会出这么新颖的题目,这个应用场景在数据库设计中确实会用到。

首先分析一下,我们应该怎么办。首先,如果给出了任意的时间,我们都要找出先于这个时间的key对应的value,说明我们必须把每次的插入结果与对应的时间都保存,而不能使用覆盖的方式。

很显然我们会使用字典这种数据结构来存储kv对,为了保存每个key插入的时间,而且要保证最快的查询时间,我分开保存每次插入的key的time和value。为什么这么做有效呢?因为如果我如果使用key : [(time1, value1), (time2, value2)...]这种存储方式,对快速查找是不利的。而使用key : [time1, time2...]key : [value1, value2...]这种存储方式能保证time和value是一一对应的。所以这种方式先根据key和time快速查找到小于该时间的timex,然后就能根据索引快速找到此索引对应的valuex.

在有序列表中快速查找小于一个time的time_x,当然使用二分了,所以使用了bisect_right来快速查找到了一个不大于该time的时间对应的索引,然后拿这个索引找到对应的value即可。

万万没想到的是,竟然没通过!我已经优化了存储和查找啊!看了下没通过的测试用例,发现是一个键值对反复的插入查找,每次查找的时间都是最新的时间。好吧,那么我使用了一个这个max_字典,用来保存当前的key更新的时间。这样的好处是,当我们查找一个不小于当前时间的值的时候,一定是最后一次插入的那个时间。

最后,说句题外话,这个题没有考到的是我们的删除操作怎么办?其实业界做法是使用延迟删除的方式,即插入一个标志位代表删除,而不进行真正的删除操作。比如我们在最后的时刻设置key为"",这样我们查找的时候发现这个key的数值是""就意味着被删除。

class TimeMap(object):

    def __init__(self):
"""
Initialize your data structure here.
"""
self.t_ = collections.defaultdict(list)
self.v_ = collections.defaultdict(list)
self.max_ = collections.defaultdict(int) def set(self, key, value, timestamp):
"""
:type key: str
:type value: str
:type timestamp: int
:rtype: None
"""
self.t_[key].append(timestamp)
self.v_[key].append(value)
self.max_[key] = max(self.max_[key], timestamp) def get(self, key, timestamp):
"""
:type key: str
:type timestamp: int
:rtype: str
"""
if key not in self.t_:
return ""
if timestamp >= self.max_[key]:
return self.v_[key][-1]
v = bisect.bisect_right(self.t_[key], timestamp)
if v:
return self.v_[key][v - 1]
return "" # Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)

日期

2019 年 1 月 27 日 —— 这个周赛不太爽

【LeetCode】981. Time Based Key-Value Store 解题报告(Python)的更多相关文章

  1. 【LeetCode】94. Binary Tree Inorder Traversal 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 递归 迭代 日期 题目地址:https://leetcode.c ...

  2. 【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归+队列 栈 日期 题目地址:https://lee ...

  3. 【LeetCode】589. N-ary Tree Preorder Traversal 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leetc ...

  4. 【LeetCode】92. Reverse Linked List II 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 题目地址:https://leet ...

  5. Leetcode 981. Time Based Key-Value Store(二分查找)

    题目来源:https://leetcode.com/problems/time-based-key-value-store/description/ 标记难度:Medium 提交次数:1/1 代码效率 ...

  6. 【LeetCode】449. Serialize and Deserialize BST 解题报告(Python)

    [LeetCode]449. Serialize and Deserialize BST 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/pro ...

  7. 【LeetCode】692. Top K Frequent Words 解题报告(Python)

    [LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...

  8. 【LeetCode】697. Degree of an Array 解题报告

    [LeetCode]697. Degree of an Array 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/degree- ...

  9. 【LeetCode】779. K-th Symbol in Grammar 解题报告(Python)

    [LeetCode]779. K-th Symbol in Grammar 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingz ...

  10. 【LeetCode】792. Number of Matching Subsequences 解题报告(Python)

    [LeetCode]792. Number of Matching Subsequences 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

随机推荐

  1. R语言与医学统计图形-【29】地图的绘制

    R绘制地图原理: R使用一个个多边形(polygon)来表示每个区域,通过顺次连接GIS数据提供的每个区域多边形的坐标来逐点绘制这些多边形,所以理论上只要得到GIS数据就可绘制相应的地图. 地图绘制说 ...

  2. 逻辑学与Prolog学习笔记

    int a = 3 + 5; 很自然.如果Matrix a, b要加呢?没有运算符重载,a + b是不行的,只能add(a, b). int a = add(3, 5)也行.如果函数名可以用+呢?+( ...

  3. accommodate ~ ache

    accommodate The accommodation reflex [反射] (or accommodation-convergence [会聚] reflex) is a reflex act ...

  4. 【讨论】APP的免填邀请码解决方案

    00x0 具体需求 app中已注册的用户分享一个含有邀请码的二维码,分享到朋友圈新用户在朋友圈打开这个这个链接下载app.新用户安装后打开app后就自动绑定邀请码要求用户不填写任何东西 朋友老板出差给 ...

  5. Hadoop、Hive【LZO压缩配置和使用】

    目录 一.编译 二.相关配置 三.为LZO文件创建索引 四.Hive为LZO文件建立索引 1.hive创建的lzo压缩的分区表 2.给.lzo压缩文件建立索引index 3.读取Lzo文件的注意事项( ...

  6. 大数据学习day23-----spark06--------1. Spark执行流程(知识补充:RDD的依赖关系)2. Repartition和coalesce算子的区别 3.触发多次actions时,速度不一样 4. RDD的深入理解(错误例子,RDD数据是如何获取的)5 购物的相关计算

    1. Spark执行流程 知识补充:RDD的依赖关系 RDD的依赖关系分为两类:窄依赖(Narrow Dependency)和宽依赖(Shuffle Dependency) (1)窄依赖 窄依赖指的是 ...

  7. OC-引用计数器,内存管理,野指针

    总结 全局断点 →-->+-->Add Exception Breakpoint 开启僵尸监听 打开Edit scheme -->Diagnostics-->Enable Zo ...

  8. Java Maven项目搭建

    创建空项目 New Project --> Empty Project --> ... 配置JDK Project Settings --> Project 选择JDK Module ...

  9. excel数据导入mySql数据库

    1.将excel数据保存好 2.打开数据库,在表上点击右键,选择导入向导 3.点击下图中红色部门,点击下一步 4.选择excel文件的位置,下方的表空间内,会出现excel中的sheet页,选择要导入 ...

  10. 【Python】文本包jieba使用

    看了一个教程:https://www.cnblogs.com/wkfvawl/p/9487165.html 有些不懂的地方自己查阅了一下 键值的添加,获得文件中相同字符出现的次数, counts = ...