Leetcode146. LRU 缓存

106 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务,点击查看活动详情

一、题目描述:

请你设计并实现一个满足  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) 的平均时间复杂度运行。

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/lr…

二、思路分析:

利用js的map是按照顺序存储的

三、AC 代码:

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

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    let map=this.map;
    if(map.has(key)){
        let v=map.get(key);
        map.delete(key);
        map.set(key,v);
        return v;
    }
    return -1;
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
    let c=this.capacity;
    let map=this.map;
    if(map.has(key)) map.delete(key);
    map.set(key,value)
    if(map.size>c){
        console.log(map.keys().next().value)
        map.delete(map.keys().next().value);
    }
};

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

四、总结:

js的map是按照顺序存储。