题解 | #设计LRU缓存结构#

设计LRU缓存结构

http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61

/**
 * lru design
 * @param operators int整型二维数组 the ops
 * @param k int整型 the k
 * @return int整型一维数组
 */
function LRU( operators ,  k ) {
    // write code here
    let arr = [];
    let map = new Map();
    for(let i = 0;i<operators.length;i++){
        if(operators[i][0] === 1){
            //set
            if(map.has(operators[i][1])){
                map.delete(operators[i][1])
                map.set(operators[i][1],operators[i][2])
            }else{
                map.set(operators[i][1],operators[i][2])
                if(map.size > k){
                    const firstKey = map.keys().next().value;//把最不常用的缓存清除
                    map.delete(firstKey);
                }
            }
        }else{
            //get
            if(map.has(operators[i][1])){
                arr.push(map.get(operators[i][1]))
                let temp = map.get(operators[i][1])
                map.delete(operators[i][1]);
              map.set(operators[i][1], temp)

            }else{
                arr.push(-1)
            }
        }
    }
    return arr
}
module.exports = {
    LRU : LRU
};
全部评论

相关推荐

每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
吴offer选手:HR:我KPI到手了就行,合不合适关我什么事
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务