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 ...
随机推荐
- http/ftp等的URL匹配正则表达式 ZT
网上流传着多种匹配URL的正则表达式版本,但我经过试验,最好用的还是从stackoverflow上查到的: (https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_| ...
- Javascript中的this指向。
一.JavaScript中的函数 在了解this指向之前,要先弄明白函数执行时它的执行环境是如何创建的,这样可以更清楚的去理解JavaScript中的this指向. function fn(x,y,n ...
- junit断言和junit注释assert
JUnit - 使用断言 断言 所有的断言都包含在 Assert 类中 public class Assert extends java.lang.Object 这个类提供了很多有用的断言方法来编写测 ...
- AspectJ的拓展学习--织入顺序和通知参数指定
前言: 其实spring的aop非常的强大, 因此研究一下AspectJ还是有必要, 而不是仅仅停留在初级的阶段. 比如spring的事务是基于aop来实现的, 如果不能深入的研究, 可能很多知识点, ...
- STL:unique()函数
unique() unique()是剔除重复他是剔除相邻之间字符重复的,倘若其中中的字符前后之间是没有重复的,unique函数是起不到作用的,所以使用以前都会sort处理. unique()函数的返回 ...
- 使用swig工具为go语言与c++进行交互
环境: centos_7_x86_x64,gcc_4.8.5 一.安装swig 1. 安装pcre yum install -y pcre pcre-tools pcre-devel 2. 安装yac ...
- spring IOC 和AOP 方面
spring 的2大核心 是Ioc 和 aop spring的依赖注入:在程序运行期间,由外部容器动态的将依赖对象注入到组件中 IOC: 实例化spring容器的二种方法 第一种:在类路径下寻找配 ...
- springboot 集成mybatis plus3
gradle: compile group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.0.1' MybatisPl ...
- 使用phpAnalysis打造PHP应用非侵入式性能分析器
使用phpAnalysis打造PHP应用非侵入式性能分析器,查找PHP性能瓶颈. 什么是phpAnalysis phpAnalysis是一款轻量级非侵入式PHP应用性能分析器,适用于开发.测试及生产环 ...
- C语言----管道
一.管道的概念 管道是一种队列类型的数据结构,它的数据从一端输入,另一端输出.管道最常见的应用是连接两个进程的输入输出,即把一个进程的输出编程另一个进程的输入.shell中存在专门的管道运算符&quo ...