题解 | #设计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;
    }
}
全部评论

相关推荐

大飞的诡术妖姬:之前看b站多明海有个说法,日本就业竞争非常低的原因不光是毕业学生少,还有很多人干两年不喜欢职场氛围就辞职躺平,位置也空了很多,论吃苦耐劳还得看咱们
点赞 评论 收藏
分享
06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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