在JavaScript中,Map
对象保存键值对,并且能够记住键的原始插入顺序。要实现删除最旧条目的操作,并且保持时间复杂度为O(1),我们可以利用Map
的特性。
Map
对象保存键值对,并且能够记住键的原始插入顺序。为了在O(1)时间内删除最旧的条目,我们可以维护一个指向最旧条目的引用。每次插入新条目时,更新这个引用。
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
this.oldestKey = null;
}
get(key) {
if (this.cache.has(key)) {
// 更新键的顺序,使其成为最新的
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
return -1; // 表示未找到
}
put(key, value) {
if (this.cache.has(key)) {
// 如果键已存在,更新其值并移动到最新位置
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
// 如果超出容量,删除最旧的条目
this.cache.delete(this.oldestKey);
}
// 插入新条目或更新现有条目
this.cache.set(key, value);
this.oldestKey = key; // 更新最旧条目的引用
}
}
// 使用示例
const cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
console.log(cache.get(1)); // 返回 1
cache.put(3, 3); // 该操作会使得键 2 作废
console.log(cache.get(2)); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得键 1 作废
console.log(cache.get(1)); // 返回 -1 (未找到)
console.log(cache.get(3)); // 返回 3
console.log(cache.get(4)); // 返回 4
Map
对象,实现简单且直观。通过上述方法,可以在JavaScript中高效地管理Map中的数据,确保最旧的条目能够被快速删除。