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

设计LRU缓存结构

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


public class Solution {
    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public Map.Entry<Integer,Integer> getHead(LinkedHashMap map) {
        return (Map.Entry<Integer,Integer>)map.entrySet().iterator().next();
    }
    public int[] LRU (int[][] operators, int k) {
        // write code here
        LinkedHashMap<Integer,Integer> map = new LinkedHashMap<>();
        ArrayList<Integer> list = new ArrayList<>();
        for(int i=0;i<operators.length;i++){
            if(operators[i][0]==1){
                if(map.containsKey(operators[i][1]))
                    map.remove(operators[i][1]);
                if(map.size()>=k)
                    map.remove(getHead(map).getKey());
                map.put(operators[i][1],operators[i][2]);
            }else{
                if(map.containsKey(operators[i][1])){
                    int value = map.get(operators[i][1]);
                    map.remove(operators[i][1]);
                    map.put(operators[i][1],value);
                    list.add(value);
                }else{
                    list.add(-1);
                }
           
            }
        }
        int []array = new int[list.size()];
        for(int i=0;i<array.length;i++){
            array[i] = list.get(i);
        }
        return array;
    }
}
全部评论

相关推荐

程序员小白条:找的太晚,别人都是大三实习,然后大四秋招春招的,你大四下了才去实习,晚1年
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 11:16
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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