146. LRU Cache
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。 实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
package leetcode
type node struct {
key,val int
prev, next *node
}
type linkedLRUCache struct {
capacity int
head,tail *node
cache map[int]*node
}
func LRUCache(capacity int) LRU {
return &linkedLRUCache{capacity:capacity,cache:make(map[int]*node)}
}
type LRU interface {
Get(key int) int
Put(key, value int)
}
func (c *linkedLRUCache) Get(key int) int {
if node,ok := c.cache[key]; ok {
c.remove(node)
c.add(node)
return node.val
}
return -1
}
func (c *linkedLRUCache) Put(key, val int) {
if n,ok := c.cache[key]; ok {
c.remove(n)
n.val = val
c.add(n)
return
}else {
n = &node{key: key,val:val}
c.cache[key] = n
c.add(n)
}
if len(c.cache) > c.capacity {
delete(c.cache,c.tail.key)
c.remove(c.tail)
}
}
//add node to head
func (c *linkedLRUCache) add(n *node) {
if c.head != nil {
c.head.prev = n
n.next = c.head
}
c.head = n
if c.tail == nil {
c.tail = n
c.tail.prev = n
c.tail.next = nil
}
}
//remove node
func (c *linkedLRUCache) remove(n *node) {
//remove head node
if c.head == n {
if n.next != nil {
n.next.prev = nil
}
c.head = n.next
return
}
//remove tail node
if c.tail == n {
c.tail = c.tail.prev
return
}
n.prev.next = n.next
n.next.prev = n.prev
}
805



被折叠的 条评论
为什么被折叠?



