文巾解题 981. 基于时间的键值存储
生活随笔
收集整理的这篇文章主要介绍了
文巾解题 981. 基于时间的键值存储
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1 题目描述
、
2 解题思路
创建两个字典,它们有相同的键,键值分别是value和timestamp
然后get的时候,我先用二分查找最大的timestamp_prev的下标,然后用这个下标定位到相应的value值
class TimeMap(object):def __init__(self):"""Initialize your data structure here."""self.dit_v=dict() #key——valueself.dit_t=dict() #key——timestampdef set(self, key, value, timestamp):""":type key: str:type value: str:type timestamp: int:rtype: None"""if(key in self.dit_v):self.dit_v[key].append(value)self.dit_t[key].append(timestamp)else:self.dit_v[key]=[value]self.dit_t[key]=[timestamp]def get(self, key, timestamp):""":type key: str:type timestamp: int:rtype: str"""if(key not in self.dit_v):return("") #字典中没有这个键值value=self.dit_v[key]time=self.dit_t[key]left=0right=len(value)-1while(left<=right):mid=(right-left)//2+leftif(time[mid]==timestamp):return(value[mid])elif(time[mid]>timestamp):right=mid-1elif(time[mid]<timestamp):left=mid+1 #二分查找if(right==-1):return("") return value[right]# Your TimeMap object will be instantiated and called as such: # obj = TimeMap() # obj.set(key,value,timestamp) # param_2 = obj.get(key,timestamp)总结
以上是生活随笔为你收集整理的文巾解题 981. 基于时间的键值存储的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: pytorch函数整理
- 下一篇: 文巾解题 178. 分数排名