Skip to content

Commit 0e3ea43

Browse files
authored
Merge pull request #3596 from drxlx/0981-time-based-key-value-store
Create 0981-time-based-key-value-store.swift
2 parents 44b0e00 + 28a8486 commit 0e3ea43

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: swift/0981-time-based-key-value-store.swift

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
class TimeMap {
3+
var store = [String: [(String, Int)]]()
4+
init() {
5+
6+
}
7+
8+
func set(_ key: String, _ value: String, _ timestamp: Int) {
9+
store[key, default: []].append((value, timestamp))
10+
}
11+
12+
func get(_ key: String, _ timestamp: Int) -> String {
13+
var res = ""
14+
var values = store[key] ?? []
15+
16+
var l = 0
17+
var r = values.count - 1
18+
while l <= r {
19+
let m = l + ((r - l) / 2)
20+
if values[m].1 <= timestamp {
21+
res = values[m].0
22+
l = m + 1
23+
} else {
24+
r = m - 1
25+
}
26+
}
27+
28+
return res
29+
}
30+
}
31+
32+
/**
33+
* Your TimeMap object will be instantiated and called as such:
34+
* let obj = TimeMap()
35+
* obj.set(key, value, timestamp)
36+
* let ret_2: String = obj.get(key, timestamp)
37+
*/

0 commit comments

Comments
 (0)