思路:

ES6 Map中keys的有序性
一个Map对象在迭代时会根据对象中元素的插入顺序来进行

get操作

如果元素存在,先delete再set, 元素便会成置为最新使用;如果不存在,返回-1

put操作

如果元素存在,先delete再set, 元素便会成置为最新使用;
如果容器超限,进行删除末尾元素操作,使用 Map{}.keys().next()得到迭代器的第一个元素,为使用时间最远的元素,进行删除

代码 :

  1. class LRUCACHE {
  2. constructor(capacity){
  3. this.capacity = capacity
  4. this.cache = new Map()
  5. }
  6. put(key, value) {
  7. if(this.cache.has(key)) {
  8. this.cache.delete(key)
  9. } else if(this.cache.size >= this.capacity) {
  10. this.cache.delete(this.cache.keys().next().value)
  11. }
  12. this.cache.set(key,value)
  13. }
  14. get(key){
  15. if(this.cache.has(key)){
  16. const temp = this.cache.get(key)
  17. this.cache.delete(key)
  18. cache.set(key, temp);
  19. return temp
  20. }else {
  21. return -1
  22. }
  23. }
  24. }