当前位置:网站首页>Leetcode 146. LRU cache
Leetcode 146. LRU cache
2022-07-04 07:43:00 【von Libniz】
Title Description
Please design and implement a meeting LRU ( Recently at least use ) cache Constrained data structure .
Realization LRUCache class :
LRUCache(int capacity) With Positive integer As capacity capacity initialization LRU cache
int get(int key) If the keyword key In the cache , The value of the keyword is returned , Otherwise return to -1 .
void put(int key, int value) If the keyword key Already exist , Change its data value value ; If it doesn't exist , Then insert the group into the cache key-value . If the insert operation causes the number of keywords to exceed capacity , Should be Eviction The longest unused keyword .
function get and put Must be O(1) The average time complexity of running .
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
explain
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // The cache is {
1=1}
lRUCache.put(2, 2); // The cache is {
1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // This operation causes the keyword to 2 To void , The cache is {
1=1, 3=3}
lRUCache.get(2); // return -1 ( Not found )
lRUCache.put(4, 4); // This operation causes the keyword to 1 To void , The cache is {
4=4, 3=3}
lRUCache.get(1); // return -1 ( Not found )
lRUCache.get(3); // return 3
Solution 1 : Hashtable + Linked list
This problem is the same as that of data flow , It's all a routine : Use a linked list to record the data sequence , Use hash table to quickly find linked list nodes , Then move the node location according to the demand . Here we use a one-way linked list to realize , Hash table storage key Corresponding value The previous node of the node . Of course, you can also directly use a two-way linked list .
class ListNode:
def __init__(self, key, value, next=None):
self.key = key
self.value = value
self.next = next
class LRUCache:
""" solution 1:HashMap + LinkedList"""
def __init__(self, capacity: int):
self.dummy = ListNode(-1, -1)
self.tail = self.dummy
self.key_to_prev = {
}
self.capacity = capacity
def get(self, key: int) -> int:
if key not in self.key_to_prev:
return -1
self.remove_to_last(key)
return self.key_to_prev.get(key).next.value
def put(self, key: int, value: int) -> None:
if key in self.key_to_prev:
self.remove_to_last(key)
self.tail.value = value
return
if len(self.key_to_prev) < self.capacity:
self.add_key_value(key, value)
return
# not enough capacity
self.remove_lru()
self.add_key_value(key, value)
def set_value(self, key, value):
pre_node = self.key_to_prev.get(key)
target_node = pre_node.next
target_node.value = value
def add_key_value(self, key, value):
new_node = ListNode(key, value)
self.key_to_prev[key] = self.tail # s
self.tail.next = new_node
self.tail = new_node
def remove_lru(self):
remove_target = self.dummy.next
self.key_to_prev.pop(remove_target.key)
self.dummy.next = remove_target.next
# capacity May be 1, So we still have to judge target.next Is it empty
if remove_target == self.tail:
self.tail = self.dummy
else:
self.key_to_prev[remove_target.next.key] = self.dummy
def remove_to_last(self, key):
pre = self.key_to_prev[key]
target = pre.next
if self.tail == target:
return
pre.next = target.next
self.key_to_prev[target.next.key] = pre
target.next = None
self.tail.next = target
self.key_to_prev[key] = self.tail
self.tail = target
Solution 2 :OrderedDict
Directly use the built-in data structure :OrderedDict.
class LRUCache:
""" solution 2:OrderedDict """
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key: int) -> int:
if key not in self.cache:
return -1
value = self.cache.pop(key) # Visited , Delete first
self.cache[key] = value # Add to the end
return value
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.pop(key) # Delete first
self.cache[key] = value # Add to the end
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
边栏推荐
- MySQL中的文本處理函數整理,收藏速查
- Used on windows Bat file startup project
- 墨者学院-phpMyAdmin后台文件包含分析溯源
- Common components of flask
- Système de surveillance zabbix contenu de surveillance personnalisé
- [web security] nodejs prototype chain pollution analysis
- When JDBC connects to es query, is there a God who meets the following situation?
- L2-013 red alarm (C language) and relevant knowledge of parallel search
- Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders
- University stage summary
猜你喜欢
随机推荐
The idea of implementing charts chart view in all swiftui versions (1.0-4.0) was born
2022-021ARTS:下半年开始
Activiti common operation data table relationship
Take you to master the formatter of visual studio code
L2-013 red alarm (C language) and relevant knowledge of parallel search
人生规划(Flag)
如何用MOS管来实现电源防反接电路
Life planning (flag)
Zephyr 學習筆記2,Scheduling
墨者学院-phpMyAdmin后台文件包含分析溯源
SQL注入测试工具之Sqli-labs下载安装重置数据库报错解决办法之一(#0{main}thrown in D:\Software\phpstudy_pro\WWW\sqli-labs-……)
Unity 从Inspector界面打开资源管理器选择并记录文件路径
Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders
BUUCTF(4)
Wechat has new functions, and the test is started again
[Android reverse] function interception (use cache_flush system function to refresh CPU cache | refresh CPU cache disadvantages | recommended time for function interception)
Rhcsa the next day
Valentine's Day is coming! Without 50W bride price, my girlfriend was forcibly dragged away...
[web security] nodejs prototype chain pollution analysis
I was pressed for the draft, so let's talk about how long links can be as efficient as short links in the development of mobile terminals