LeetCode: 146. LRU Cache

思考过程:
1.cache的长度确定。
2.get方法如果获取到数据则返回,获取不到则返回-1.
3.put方法如果长度超过限制则替换掉访问最少的值。这是否意味着需要有个计数?
4.如果有个计数来统计访问量,该如何保证时间复杂度是O(1)?
5.不如维护一个链表和一个map。利用map快速定位到链表中的元素,如果找到元素,则将对应链表元素放置道开头;调用put方法时可以快速利用

function Node(key, element) {
    this.element = element;
    this.key = key;
    this.next = null;
    this.prev = null;
}

function List() {
    this.head = new Node("head", "head");
    this.tail = this.head;
}


List.prototype.delete = function(item) {
    if(item.next == null) {
        item.prev.next = null;
        this.tail = item.prev;
    } else {
        item.prev.next = item.next;
        item.next.prev = item.prev;
    }
}

List.prototype.push = function(item) {
    if(this.head.next == null) {
        this.head.next = item;
        item.prev = this.head;
        this.tail = item;
    } else {
        item.next = this.head.next;
        item.next.prev = item;
        item.prev = this.head;
        this.head.next = item;
    }
}

List.prototype.deleteTail = function() {
    if(this.tail.prev == null) {
        return false;   
    } else {
        var oldTail = this.tail;
        var prevNode = this.tail.prev;
        prevNode.next = null;
        this.tail = prevNode;
    }
    return oldTail;
}

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.capacity = capacity;
    this.cache = new List();
    this.map = {};
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {

    if(this.map[key]) {
        this.cache.delete(this.map[key]);
        this.cache.push(this.map[key]);
        
        return this.map[key].element;
    }
    
    return -1;
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {

    // if key exist
    if(this.map[key]) {
        this.cache.delete(this.map[key]);
    } else if(Object.keys(this.map).length >= this.capacity) {
        var tail = this.cache.deleteTail();
        delete this.map[tail.key];
    }
    this.map[key] = new Node(key, value);
    this.cache.push(this.map[key]);
};

/** 
 * 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)
 */

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值