当前位置:网站首页>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)
边栏推荐
- Rhcsa the next day
- Jianmu continuous integration platform v2.2.2 release
- 墨者学院-Webmin未经身份验证的远程代码执行
- 促进OKR落地的工作总结该如何写?
- Zephyr study notes 2, scheduling
- NPM run build error
- OKR vs. KPI figure out these two concepts at once!
- L1-027 rental (20 points)
- Literature collation and thesis reading methods
- L1-025 positive integer a+b (15 points)
猜你喜欢

This article is enough for learning advanced mysql

Heap concept in JVM

Technical experts from large factories: common thinking models in architecture design

节点基础~节点操作

Flask 常用组件

线性代数1.1

大学阶段总结

Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders

时序数据库 InfluxDB 2.2 初探

The cloud native programming challenge ended, and Alibaba cloud launched the first white paper on application liveliness technology in the field of cloud native
随机推荐
Two years ago, the United States was reluctant to sell chips, but now there are mountains of chips begging China for help
Basic DOS commands
The idea of implementing charts chart view in all swiftui versions (1.0-4.0) was born
The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)
L2-013 red alarm (C language) and relevant knowledge of parallel search
This article is enough for learning advanced mysql
NPM run build error
SQL注入测试工具之Sqli-labs下载安装重置数据库报错解决办法之一(#0{main}thrown in D:\Software\phpstudy_pro\WWW\sqli-labs-……)
Application of isnull in database query
How to write a summary of the work to promote the implementation of OKR?
zabbix监控系统邮件报警配置
墨者学院-phpMyAdmin后台文件包含分析溯源
Zephyr learning notes 1, threads
论文学习——基于极值点特征的时间序列相似性查询方法
L1-022 odd even split (10 points)
ZABBIX monitoring system deployment
[gurobi] establishment of simple model
[Flink] temporal semantics and watermark
The IP bound to the socket is inaddr_ The meaning of any htonl (inaddr_any) (0.0.0.0 all addresses, uncertain addresses, arbitrary addresses)
BibTex中参考文献种类