|
| 1 | +/** |
| 2 | + * [146] LRU Cache |
| 3 | + * |
| 4 | + * |
| 5 | + * Design and implement a data structure for <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU" target="_blank">Least Recently Used (LRU) cache</a>. It should support the following operations: get and put. |
| 6 | + * |
| 7 | + * |
| 8 | + * |
| 9 | + * get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.<br> |
| 10 | + * put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. |
| 11 | + * |
| 12 | + * |
| 13 | + * Follow up:<br /> |
| 14 | + * Could you do both operations in O(1) time complexity? |
| 15 | + * |
| 16 | + * Example: |
| 17 | + * |
| 18 | + * LRUCache cache = new LRUCache( 2 /* capacity */ ); |
| 19 | + * |
| 20 | + * cache.put(1, 1); |
| 21 | + * cache.put(2, 2); |
| 22 | + * cache.get(1); // returns 1 |
| 23 | + * cache.put(3, 3); // evicts key 2 |
| 24 | + * cache.get(2); // returns -1 (not found) |
| 25 | + * cache.put(4, 4); // evicts key 1 |
| 26 | + * cache.get(1); // returns -1 (not found) |
| 27 | + * cache.get(3); // returns 3 |
| 28 | + * cache.get(4); // returns 4 |
| 29 | + * |
| 30 | + * |
| 31 | + */ |
| 32 | + |
| 33 | +// submission codes start here |
| 34 | + |
| 35 | +/* |
| 36 | + Least Recently Used, 最近最少使用, 关键在于追踪每一个 entry 的 age, 每次淘汰最小的那一个 key |
| 37 | +
|
| 38 | + 假如淘汰逻辑要做到 O(1) 复杂度, 我们可以引入一个链表, 每次 touch 一个值时, 就删掉它重新 push_back, 而当达到容量要驱逐时, 则 pop_front |
| 39 | +
|
| 40 | + Rust 的链表不支持根据引用删除任意元素,这个工程实现还是有点挑战的, 晚点再做 |
| 41 | + */ |
| 42 | +use std::collections::HashMap; |
| 43 | +use std::collections::LinkedList; |
| 44 | +struct LRUCache { |
| 45 | + cache: HashMap<i32, i32>, |
| 46 | + vec: Vec<i32>, |
| 47 | + cap: i32, |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * `&self` means the method takes an immutable reference. |
| 52 | + * If you need a mutable reference, change it to `&mut self` instead. |
| 53 | + */ |
| 54 | +impl LRUCache { |
| 55 | + |
| 56 | + fn new(capacity: i32) -> Self { |
| 57 | + LRUCache{ |
| 58 | + cache: HashMap::with_capacity(capacity as usize,), |
| 59 | + vec: Vec::with_capacity(capacity as usize), |
| 60 | + cap: capacity, |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + fn get(&mut self, key: i32) -> i32 { |
| 65 | + let cache = HashMap::new(); |
| 66 | + let list = Vec::new(); |
| 67 | + } |
| 68 | + |
| 69 | + fn put(&mut self, key: i32, value: i32) { |
| 70 | + |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +// submission codes end |
| 75 | + |
| 76 | +#[cfg(test)] |
| 77 | +mod tests { |
| 78 | + use super::*; |
| 79 | + |
| 80 | + #[test] |
| 81 | + fn test_146() { |
| 82 | + } |
| 83 | +} |
0 commit comments