forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0981-Time-Based-Key-Value-Store.rb
54 lines (44 loc) · 1.11 KB
/
0981-Time-Based-Key-Value-Store.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class TimeMap
def initialize()
@map = {}
end
=begin
:type key: String
:type value: String
:type timestamp: Integer
:rtype: Void
=end
def set(key, value, timestamp)
@map[key] = [] unless @map.key?(key)
@map[key] << { v: value, t: timestamp }
end
=begin
:type key: String
:type timestamp: Integer
:rtype: String
=end
def get(key, timestamp)
return "" unless @map.key?(key)
entries = @map[key]
return "" if timestamp < entries[0][:t]
return entries[-1][:v] if timestamp >= entries[-1][:t]
l = 0
r = entries.length - 1
max = entries[0]
while l <= r
mid = ( l + r ) / 2
curr = entries[mid]
if curr[:t] < timestamp
max = curr
l = mid + 1
else
r = mid - 1
end
end
max[:v]
end
end
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap.new()
# obj.set(key, value, timestamp)
# param_2 = obj.get(key, timestamp)