这是我参与8月更文挑战的第10天,活动详情查看:8月更文挑战
146. LRU 缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。 实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存 int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。 void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]
解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4
解题思路
基于链表和hashmap实现LRU
- 每次新增key的时候,如果key已经存在了,就将key移到链表头,并且修改value。如果key不存在,直接将key插入队头。如果已经超出LRU的大小,就删除链表尾部的key
- 每次get的时候,如果key存在,就将这个key移到链表头,并且返回
代码
type LRUCache struct {
capacity int
head *Node
tail *Node
cache map[int]*Node
}
type Node struct {
pre *Node
next *Node
key int
val int
}
var c LRUCache
func Constructor(capacity int) LRUCache {
c.cache= map[int]*Node{}
c.capacity=capacity
c.head=&Node{val: -1}
c.tail=&Node{val: -1}
c.head.next=c.tail
c.tail.pre=c.head
return c
}
func (lru *LRUCache) Get(key int) int {
node,ok := c.cache[key]
if ok {
p,n := node.pre,node.next
p.next=n
n.pre=p
th:=lru.head.next
//插入头节点
lru.head.next=node
node.pre=lru.head
node.next=th
th.pre=node
return node.val
}
return -1
}
func (lru *LRUCache) Put(key int, value int) {
if lru.Get(key)!=-1 {
lru.head.next.val=value
return
}
if lru.capacity==0 {
delete(lru.cache,lru.tail.pre.key)
tl := lru.tail.pre.pre
tl.next=lru.tail
lru.tail.pre=tl
lru.capacity++
}
node := &Node{
key: key,
val: value,
next: lru.head.next,
pre: lru.head,
}
lru.head.next.pre=node
lru.head.next=node
lru.cache[key]=node
lru.capacity--
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/