思路:
ES6 Map中keys的有序性
一个Map对象在迭代时会根据对象中元素的插入顺序来进行
get操作
如果元素存在,先delete再set, 元素便会成置为最新使用;如果不存在,返回-1
put操作
如果元素存在,先delete再set, 元素便会成置为最新使用;
如果容器超限,进行删除末尾元素操作,使用 Map{}.keys().next()得到迭代器的第一个元素,为使用时间最远的元素,进行删除
代码 :
class LRUCACHE {constructor(capacity){this.capacity = capacitythis.cache = new Map()}put(key, value) {if(this.cache.has(key)) {this.cache.delete(key)} else if(this.cache.size >= this.capacity) {this.cache.delete(this.cache.keys().next().value)}this.cache.set(key,value)}get(key){if(this.cache.has(key)){const temp = this.cache.get(key)this.cache.delete(key)cache.set(key, temp);return temp}else {return -1}}}
