请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
LRUCache(int capacity)以 正整数 作为容量capacity初始化 LRU 缓存int get(int key)如果关键字key存在于缓存中,则返回关键字的值,否则返回-1。void put(int key, int value)如果关键字key已经存在,则变更其数据值value;如果不存在,则向缓存中插入该组key-value。如果插入操作导致关键字数量超过capacity,则应该 逐出 最久未使用的关键字。
函数 get 和 put 必须以 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
提示:
1 <= capacity <= 30000 <= key <= 100000 <= value <= 105- 最多调用
2 * 105次get和put
TypeScript
class LRUCache {
private capacity:number
private newM:Map<number,number>
constructor(capacity: number) {
this.capacity = capacity
this.newM = new Map()
}
get(key: number): number {
if(this.newM.has(key)){
const value = this.newM.get(key)!
this.newM.delete(key)
this.newM.set(key,value)
return value
}else{
return -1
}
}
put(key: number, value: number): void {
if(this.newM.has(key)){
this.newM.delete(key)
this.newM.set(key,value)
}else{
this.newM.set(key,value)
if(this.newM.size > this.capacity){
const trail = this.newM.keys().next().value
this.newM.delete(trail)
}
}
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
这是用内置的数据结构Map实现的,核心在于.set()方法可以记住插入的顺序,可以获取最早插入的元素。
1.初始化Map对象
2.put操作:
Map里有该key,删掉原来的键值对,重新插入;
Map里没有该key,直接插入;判断Map长度,大于capacity,把第一个set的元素删除;
3.get操作:
Map里有该key,保存原来的value值,删掉原来的key键值对,再重新set把键值对存进Map,这里是让Map给set重新记录顺序。
Map没有该key,返回-1
注意:set()方法可以记录Map增加元素的顺序Map.keys(),获取按顺序排列好的key
.next().value,获取第一个key的value值
共勉