What is LRU Cache and How to Implement it
1. What is LRU Cache
LRU is the abbreviation of Least Recently Used, which means least recently used. It is a Cache replacement algorithm.
1.1 What is Cache?
The Cache in the narrow sense refers to the fast RAM located between the CPU and the main memory. Usually it does not use DRAM technology like the system main memory, but uses the expensive but faster SRAM technology. The Cache in the broad sense refers to the fast RAM located between the CPU and the main memory. A structure used to coordinate the difference in data transmission speed between the two types of hardware. In addition to the Cache between the CPU and the main memory, there is also a Cache between the memory and the hard disk, and even between the hard disk and the network in a certain sense. Cache - known as temporary Internet files or network content cache etc.
2. Why Need LRU Algorithm
The capacity of Cache is limited, so when the capacity of Cache is used up (in fact, it will not really be used up, there will be a water level. If the remaining capacity is lower than this water level, the LRU algorithm needs to be executed), new content will be added. you need to select and discard some of the original content to make room for new content. The replacement principle of LRU Cache is to replace the least recently used content.
3. How to Implement LRU Cache
There are many methods and ideas to implement LRU Cache, but to maintain efficient implementation of O(1) put and get, it is the most efficient and classic to use a doubly linked list and a hash table. Doubly linked lists are used because doubly linked lists can achieve any The insertion and deletion at position O(1) uses a hash table because the addition, deletion, and modification of a hash table is also O(1).
3.1 Code Example
1 |
|