LeetCode Daily Question 12
3 月 17 日 每日一题
题目:146. LRU Cache
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
int get(int key) Return the value of the key if the key exists, otherwise return -1.
void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
The functions get and put must each run in O(1) average time complexity.
1 | Input |
思路
这道题出现的时间很合适,刚好 370 讲到 Cache。
本题的思路是使用一个 list 存储 key/value pairs,通过对 pair 位置的调整,以实现 front 为 most recently used,back 为 least recently used。
为了达到 O(1)的 search,我们还需要用一个 hashmap 存储指向每一个 pair 的 iterator,并以 pair 的 key 作为 hashmap 的 key。
实现时通过 splice 将一个 node 移动到 list 的 front。put 可以分为三种情况:exit, not exit && full 和 not exit & not full。顺便 map 的 erase 既可以使用 iterator,也可以直接用 key。
代码
1 | class LRUCache { |