当前位置:网站首页>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)
边栏推荐
- Set and modify the page address bar icon favicon ico
- 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
- Jianmu continuous integration platform v2.2.2 release
- How does dataframe calculate the average value of each row as another column
- [real case] how to deal with the failure of message consumption?
- Blue Bridge Cup Quick sort (code completion)
- JVM中堆概念
- 2022 - 021arts: début du deuxième semestre
- R language uses cforest function in Party package to build random forest based on conditional inference trees, uses varimp function to check feature importance, and uses table function to calculate co
- Activiti common operation data table relationship
猜你喜欢

User login function: simple but difficult

Xcode 14之大变化详细介绍

Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
![[Android reverse] function interception (use cache_flush system function to refresh CPU cache | refresh CPU cache disadvantages | recommended time for function interception)](/img/5c/afb0d43665a8b46579dc604d983790.jpg)
[Android reverse] function interception (use cache_flush system function to refresh CPU cache | refresh CPU cache disadvantages | recommended time for function interception)

Blog stop statement

Zephyr 学习笔记1,threads

Chrome is set to pure black

L2-013 red alarm (C language) and relevant knowledge of parallel search

在所有SwiftUI版本(1.0-4.0)中原生实现Charts图表视图之思路

Comparison between applet framework and platform compilation
随机推荐
L1-030 one gang one (15 points)
MySQL error resolution - error 1261 (01000): row 1 doesn't contain data for all columns
Blog stop statement
如何用MOS管来实现电源防反接电路
How to write a summary of the work to promote the implementation of OKR?
Introduction to neural network (Part 2)
BUUCTF(3)
Zephyr learning notes 1, threads
Div hidden in IE 67 shows blank problem IE 8 is normal
Advanced MySQL: Basics (5-8 Lectures)
墨者学院-Webmin未经身份验证的远程代码执行
Activiti common operation data table relationship
Mysql database - function constraint multi table query transaction
It's healthy to drink medicinal wine like this. Are you drinking it right
Go h*ck yourself:online reconnaissance (online reconnaissance)
Devops Practice Guide - reading notes (long text alarm)
Zephyr 學習筆記2,Scheduling
Life planning (flag)
Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
BUUCTF(4)