(LRU)latest recently used 基于哈希链表实现复杂度为O(1)的缓存策略
function No(key, val) {
this.next = null
this.prev = null
this.key = key
this.val = val
}
function DoubleList() {
this.head = null
this.tail = null
this.size = 0
}
DoubleList.prototype.addFirst = function(node) {
if (this.size < 1) {
this.head = node
this.tail = node
} else {
node.next = this.head
this.head.prev = node
this.head = node
}
this.size++
}
DoubleList.prototype.remove = function(node) {
if (this.size < 1) return
if (node.next === null && node.prev === null) {
this.head = null
this.tail = null
} else if (node.next === null) {
this.tail = node.prev
this.tail.next = null
} else if (node.prev === null) {
this.head = node.next
this.head.prev = null
} else {
node.next.prev = node.prev
node.prev.next = node.next
}
this.size--
}
DoubleList.prototype.removeLast = function() {
const lastNode = this.tail
this.remove(this.tail)
return lastNode
}
function LRUCache(capacity) {
this.hashMap = new Map()
this.cache = new DoubleList()
this.cap = capacity
}
LRUCache.prototype.put = function(key, val) {
const node = new No(key, val)
if (this.hashMap.get(key) !== undefined) {
this.cache.remove(this.hashMap.get(key))
this.cache.addFirst(node)
this.hashMap.set(key, node)
} else {
if (this.cap === this.cache.size) {
const lastNode = this.cache.removeLast()
this.hashMap.delete(lastNode.key)
}
this.cache.addFirst(node)
this.hashMap.set(key, node)
}
}
LRUCache.prototype.get = function(key) {
if (this.hashMap.get(key) === undefined) {
return -1
}
const node = this.hashMap.get(key)
this.put(key, node.val)
return node.val
}
测试
LRUCache cache = new LRUCache( 2 );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);
cache.put(3, 3);
cache.get(2);
cache.put(4, 4);
cache.get(1);
cache.get(3);
cache.get(4);