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

设计LRU缓存结构

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

import java.util.*;


public class Solution {
    Map<Integer, Integer> map;
    int capacity;
    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU (int[][] operators, int k) {
        // write code here
        this.capacity = k;
        map = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true){

            protected boolean removeEldestEntry(Map.Entry eldest){
                return size()>capacity;
            }
        };
        
        List<Integer> res = new ArrayList<>();
        for(int i = 0; i< operators.length;i++){
            if(operators[i][0] == 1){
                set(operators[i][1], operators[i][2]);
            }else{
                res.add(get(operators[i][1]));
            }
        }
        
        return res.stream().mapToInt(Integer::valueOf).toArray();
    }
    
    public void set(int key, int val){
        map.put(key, val);
    }
    
    public Integer get(int key){
        return map.getOrDefault(key, -1);
    }
}
全部评论

相关推荐

每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
06-06 03:40
已编辑
电子科技大学 Java
在秋招的小白菜很想养修勾:一眼 苍穹外卖+谷粒商城,项目换一换吧,可以找一些付费知识星球博主带带,避免烂大街。多投投大厂,背背八股,你这学历乱杀了,等实习经验到位,到时候大厂闭眼选
投递美团等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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