-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime-based-key-value-store.rs
72 lines (63 loc) · 2.25 KB
/
time-based-key-value-store.rs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
https://leetcode.com/problems/time-based-key-value-store/
use std::collections::HashMap;
use std::cmp::Ordering;
struct TimeMap {
store: HashMap<String, Vec<(i32, String)>>
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl TimeMap {
fn new() -> Self {
Self { store: HashMap::new() }
}
fn set(&mut self, key: String, value: String, timestamp: i32) {
match self.store.get_mut(&key) {
Some(val_snaps) => {
let pos = val_snaps.binary_search_by(|item| item.0.cmp(×tamp))
.unwrap_or_else(|elm| elm);
val_snaps.insert(pos, (timestamp, value));
},
_ => {
let mut first_snap = Vec::new();
first_snap.push((timestamp, value));
self.store.insert(key, first_snap);
}
};
}
fn get(&self, key: String, timestamp: i32) -> String {
match self.store.get(&key) {
Some(val_snaps) => {
if val_snaps.first().unwrap().0 > timestamp { return Self::default_value() }
let mut low = 0 as i32;
let mut high = (val_snaps.len() - 1) as i32;
let mut max = val_snaps.first().unwrap();
while low <= high {
let mid = (low + high) / 2;
let item = &val_snaps[mid as usize];
match item.0.cmp(×tamp) {
Ordering::Less => {
if max.0 < item.0 { max = &item }
low = mid + 1
},
Ordering::Greater => {
high = mid - 1},
Ordering::Equal => return item.1.clone(),
}
}
return max.1.clone();
},
_ => Self::default_value(),
}
}
fn default_value() -> String{
"".to_string()
}
}
/**
* Your TimeMap object will be instantiated and called as such:
* let obj = TimeMap::new();
* obj.set(key, value, timestamp);
* let ret_2: String = obj.get(key, timestamp);
*/