题解 | #设计LRU缓存结构# java版本解法

设计LRU缓存结构

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

import java.util.*;


public class Solution {
    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU (int[][] operators, int k) {
        //存放结果数组
        List<Integer> result = new ArrayList<>();
        
        //存放LRU数据,用于判断谁是最少使用的
        List<String> list = new ArrayList<>();
        //存放对应的key、value
        Map<String,Integer> map = new HashMap<>();
        
        for(int i = 0; i< operators.length; i++) {
            int opt = operators[i][0];
            String key =  String.valueOf(operators[i][1]);
            if(opt == 1) {
                //每次插入时判断是否需要删除
                if(list.size() >= k) {
                    map.remove(list.get(0));
                    list.remove(0);
                }
                list.add(key);
                map.put(key,operators[i][2]);
            } else {
                Integer value = map.get(key);
                result.add(value == null ? -1 : value);
                //每次取值后要把原值的权重刷新
                if(value != null) {
                    list.remove(key);
                    list.add(key);
                }
            }
        }
        return result.stream().mapToInt(Integer::valueOf).toArray();
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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