Skip to content

Commit 7227bc9

Browse files
authored
Create 0981-time-based-key-value-store.rs
1 parent 973981e commit 7227bc9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use std::collections::HashMap;
2+
3+
struct TimeMap {
4+
hm: HashMap::<String, Vec<(String, i32)>>
5+
}
6+
7+
impl TimeMap {
8+
9+
fn new() -> Self {
10+
Self {
11+
hm: HashMap::new()
12+
}
13+
}
14+
15+
fn set(&mut self, key: String, value: String, timestamp: i32) {
16+
self.hm.entry(key).or_default().push((value, timestamp));
17+
}
18+
19+
fn get(&self, key: String, timestamp: i32) -> String {
20+
let mut res = String::new();
21+
22+
if let Some(t_list) = self.hm.get(&key) {
23+
let (mut l, mut r) = (0, t_list.len());
24+
25+
while l < r {
26+
let m = l + (r - l) / 2;
27+
if timestamp < t_list[m].1 {
28+
r = m;
29+
} else {
30+
res = t_list[m].0.clone();
31+
l = m + 1;
32+
}
33+
}
34+
}
35+
36+
res
37+
}
38+
}

0 commit comments

Comments
 (0)