算法(1)——LRU

164 阅读1分钟

(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
}

// LRU
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);       // 返回  1
cache.put(3, 3);    // 该操作会使得关键字 2 作废
cache.get(2);       // 返回 -1 (未找到)
cache.put(4, 4);    // 该操作会使得关键字 1 作废
cache.get(1);       // 返回 -1 (未找到)
cache.get(3);       // 返回  3
cache.get(4);       // 返回  4