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 ...
随机推荐
- Problem E: 平面上的点——Point类 (V)
Description 在数学上,平面直角坐标系上的点用X轴和Y轴上的两个坐标值唯一确定.现在我们封装一个“Point类”来实现平面上的点的操作. 根据“append.cc”,完成Point类的构造方 ...
- Alpha冲刺6
前言 队名:拖鞋旅游队 组长博客:https://www.cnblogs.com/Sulumer/p/10004107.html 作业博客:https://edu.cnblogs.com/campus ...
- 剑指Offer 48. 不用加减乘除做加法 (其他)
题目描述 写一个函数,求两个整数之和,要求在函数体内不得使用+.-.*./四则运算符号. 题目地址 https://www.nowcoder.com/practice/59ac416b4b944300 ...
- python基础--列表、元祖、字典、集合
列表(List) 1.列表特点 列表是可变的!! list 是一种有序的序列,可以添加.删除其中的元素,并且可以通过下标(索引)访问 数据 2.简单的常用操作 A.通过下表访问元素 print(lis ...
- 文笔很差系列1 - 也谈谈AlphaGo
距离AlphaGo击败李世石已经过去数月了,心中的震撼至今犹在,全刊报道此项比赛的<围棋天地>杂志我已经看了不下十遍.总也想说点自己的意见,却也不知道从哪里说起,更不知道想表达些什么. 作 ...
- mql初学事物和视图
1.概念:一条或者多条sql语句的集合! 事务:就是一堆操作的集合,他们同生共死.要么都执行成功,要么都执行失败 2.事务的特性 ACID A:原子性 完整的,不可分割的 原子性 (Atomicity ...
- day05 判断敏感字符
1.判断一个字符是不是敏感字符: in 1.str v ="年龄多大了" if "大" in v: print("敏感") 2.list/t ...
- python: 递归函数(科赫雪花)
import turtle as t def kehe(size,n): #递归函数 if n==0: t.fd(size) #阶数为0时,为一直线 else: for i in [0,60,-120 ...
- PythonStudy——魔法函数 Magic Methods
魔法函数 python中以双下划线开始和结束的函数(不可自己定义)为魔法函数 调用类实例化的对象的方法时自动调用魔法函数(感觉不需要显示调用的函数都叫) 在自己定义的类中,可以实现之前的内置函数,比如 ...
- alias重命名命令
升级了openssh后,发现ctrl+l忽然无法清屏了. 如果需要清屏的话,就得执行clear,但我更喜欢简单粗暴的做法,于是想起alias命令 方式一: 如果只想在当前终端生效(exit该窗口终端后 ...