Skip to content

Commit 59bb906

Browse files
authored
Merge pull request neetcode-gh#1294 from voski/patch-9
Create 0981-Time-Based-Key-Value-Store.rb
2 parents 6ec4172 + 7fc99fe commit 59bb906

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class TimeMap
2+
def initialize()
3+
@map = {}
4+
end
5+
6+
7+
=begin
8+
:type key: String
9+
:type value: String
10+
:type timestamp: Integer
11+
:rtype: Void
12+
=end
13+
def set(key, value, timestamp)
14+
@map[key] = [] unless @map.key?(key)
15+
16+
@map[key] << { v: value, t: timestamp }
17+
end
18+
19+
20+
=begin
21+
:type key: String
22+
:type timestamp: Integer
23+
:rtype: String
24+
=end
25+
def get(key, timestamp)
26+
return "" unless @map.key?(key)
27+
28+
entries = @map[key]
29+
return "" if timestamp < entries[0][:t]
30+
return entries[-1][:v] if timestamp >= entries[-1][:t]
31+
32+
l = 0
33+
r = entries.length - 1
34+
max = entries[0]
35+
while l <= r
36+
mid = ( l + r ) / 2
37+
curr = entries[mid]
38+
39+
if curr[:t] < timestamp
40+
max = curr
41+
l = mid + 1
42+
else
43+
r = mid - 1
44+
end
45+
end
46+
47+
max[:v]
48+
end
49+
end
50+
51+
# Your TimeMap object will be instantiated and called as such:
52+
# obj = TimeMap.new()
53+
# obj.set(key, value, timestamp)
54+
# param_2 = obj.get(key, timestamp)

0 commit comments

Comments
 (0)