leetcode981
考虑线性的搜索会超时,所以用二叉搜索来解决,代码如下:
class TimeMap:
def __init__(self):
self.ST = dict() def set(self, key: 'str', value: 'str', timestamp: 'int') -> 'None':
if key in self.ST.keys():
D = self.ST[key]#dict
D.update({timestamp:value})
self.ST.update({key:D})
else:
D = dict()
D.update({timestamp:value})
self.ST.update({key:D}) def get(self, key: 'str', timestamp: 'int') -> 'str':
if key in self.ST.keys():
D = self.ST[key]
V = self.binSearch(timestamp,D)
return V
else:
return '' def binSearch(self,target,D):
times = list(D.keys())
n = len(times)
minval = times[0]
maxval = times[-1]
if target < minval:
return '' if target == minval:
return D[times[0]] if target >= maxval:
return D[times[-1]] left = 0
right = n - 1
while left < right:
mid = (left + right) // 2
if times[mid] == target:
return D[times[mid]]
elif times[mid]<target:
left = mid + 1
elif times[mid]>target:
right = mid - 1
if left == 0:
return D[times[left]]
else:
return D[times[left-1]]
但是这种写法会超时,这应该是代码质量问题,目前没明白是啥原因。
哪位博友知道我的代码的问题,欢迎告知。
参考了一下别人的方案,看到一个线性搜索的解决方案,却可以通过。
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
def set(self, key: 'str', value: 'str', timestamp: 'int') -> 'None':
if key in self.dic:
self.dic[key].append({'v': value, 't': timestamp})
else:
self.dic[key] = [{'v': value, 't': timestamp}]
def get(self, key: 'str', timestamp: 'int') -> 'str':
if key in self.dic:
for kv in reversed(self.dic[key]):
if timestamp >= kv['t']:
return kv['v']
return ""
else:
return ""
leetcode981的更多相关文章
- [Swift]LeetCode981. 基于时间的键值存储 | Time Based Key-Value Store
Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, s ...
随机推荐
- 关于Java的特点之多态
多态--概念 所谓多态,就是指一个引用(类型)在不同情况下的多种状态.也可以理解成:多态是指通过指向父类的指针,来调用在不同子类中实现的方法. 实现多态有两种方式:1.继承:2.接口 多态--注意事项 ...
- Spring 源码学习(1)—— 容器的基本实现
最近在读Spring的源码,参考的是郝佳的<Spring源码深度解析>,这里把一些学习心得分享一下,总结的地方可能还有一些不完善,希望大家指教 IoC(控制反转)是Spring的特性之一, ...
- HTML5:图片、音乐和视频
图片.音乐和视频 一.图片 1.属性 属性 说明 alt 规定图像的替代文本. src 规定显示图像的 URL align 规定如何根据周围的文本来排列图像. border 定义图像周围的边框. he ...
- Echarts tooltip 坐标值修改
tooltip: { trigger: 'axis', position:function(p){ //其中p为当前鼠标的位置 console.log(p); ] + , p[] - ]; } },
- groupmod语法
语法 groupmod [-g <群组识别码> <-o>][-n <新群组名称>][群组名称] 参数: -g <群组识别码> 设置欲使用的群组识别码. ...
- 神州数码广域网PPP封装PAP认证配置
实验要求:熟练掌握PAP认证配置(单向.双向) 拓扑如下: 单向 R1(验证方) enable 进入特权模式 config 进入全局模式 hostname R1 修改名称 interface s0/ ...
- 使用pip命令自动生成项目安装依赖清单
Python项目中经常会带requirements.txt文件,里面是项目所依赖的包的列表,也就是依赖关系清单,这个清单也可以使用pip命令自动生成. pip命令: 1 pip freeze > ...
- UVa839
这个引用好精髓. #include <iostream> #include <cstring> #include <string> #include <map ...
- linux的基本操作3(权限)
sudo cat /etc/passwd 查看账户信息用户有自己的编号是uid,组也有自己的编号是giduseradd -D 查看默认添加账号的模板sudo useradd -m liu 添加带h ...
- web driver下载地址(selenium-3.141_浏览器版本对应)
web driver: (Windows环境下) Firefox(上一目录可以找其他浏览器的driver) : 1)http://npm.taobao.org/mirrors/geckodriver/ ...