文巾解题 981. 基于时间的键值存储
生活随笔
收集整理的這篇文章主要介紹了
文巾解题 981. 基于时间的键值存储
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 題目描述
、
?2 解題思路
創(chuàng)建兩個字典,它們有相同的鍵,鍵值分別是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. 分数排名