-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0146_lru_cache.rs
More file actions
64 lines (54 loc) · 1.44 KB
/
s0146_lru_cache.rs
File metadata and controls
64 lines (54 loc) · 1.44 KB
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
#![allow(unused)]
use std::convert::TryInto;
use std::collections::VecDeque;
use std::collections::HashMap;
struct LRUCache {
dq: VecDeque<i32>,
map: HashMap<i32, i32>,
cap: usize,
}
impl LRUCache {
fn new(capacity: i32) -> Self {
Self {
dq: VecDeque::new(),
map: HashMap::new(),
cap: capacity.try_into().unwrap(),
}
}
fn get(&mut self, key: i32) -> i32 {
if self.map.contains_key(&key) {
let i = self.dq.iter().position(|&x| x == key).unwrap();
self.dq.remove(i);
self.dq.push_front(key);
return self.map.get(&key).cloned().unwrap();
}
-1
}
fn put(&mut self, key: i32, value: i32) {
if self.map.contains_key(&key) {
let i = self.dq.iter().position(|&x| x == key).unwrap();
self.dq.remove(i);
self.dq.push_front(key);
self.map.insert(key, value);
} else {
if self.map.len() == self.cap {
let last = self.dq.pop_back().unwrap();
self.map.remove(&last);
}
self.map.insert(key, value);
self.dq.push_front(key);
}
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* let obj = LRUCache::new(capacity);
* let ret_1: i32 = obj.get(key);
* obj.put(key, value);
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_346() {}
}