146.LRU缓存机制

195 阅读1分钟

LRU缓存机制

题目描述

运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制 。 实现 LRUCache 类:

LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存 int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。 void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。  

进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?

来源:力扣(LeetCode)

题解

hash表+双链表 Tips:使用首尾指针守卫代码就会变的好写很多

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
  this.max = capacity;
  this.map = Object.create(null);
  this.size = 0;
  this.head = new LinkNode();
  this.tail = new LinkNode();
  this.head.next = this.tail;
  this.tail.pre = this.head;
};

/**
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
  const current = this.map[key]
  if (current){
    this.deleteNode(current);
    this.insertHead(current);
    return current.val;
  }
  return -1;
};

/**
 * @param {number} key
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
  const current = this.map[key]
  if (current){
    current.val = value;
    this.get(key)
  } else {
    if (this.size === this.max){
      this.map[this.tail.pre.key] = undefined
      this.deleteNode(this.tail.pre)
      this.size--
    }
    const current = new LinkNode(key,value);
    this.insertHead(current)
    this.map[key] = current
    this.size++
  }
};
/**
 *
 * @param {LinkNode}node
 */
LRUCache.prototype.deleteNode = function (node) {
  node.pre.next = node.next;
  node.next.pre = node.pre;
  node.next = null;
  node.pre = null;
}

/**
 *
 * @param {LinkNode}node
 */
LRUCache.prototype.insertHead = function (node) {
  node.next = this.head.next;
  this.head.next.pre = node;
  node.pre = this.head;
  this.head.next = node;
}
/**
 * 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)
 */


/**
 *
 * @param {number}key
 * @param {number}val
 * @param {LinkNode,null}pre
 * @param {LinkNode,null}next
 * @constructor
 */
function LinkNode(key=0,val=0,pre=null,next=null) {
  this.key = key;
  this.val = val;
  this.pre = pre;
  this.next = next;
}