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

设计LRU缓存结构

http://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84

import java.util.*;


public class Solution {
    
    private LinkedHashMap<Integer, Integer> linkedHashMap;
    private int capacity;
    
    // 构造函数
    public Solution(int capacity) {
         // write code here
        this.capacity = capacity;
        linkedHashMap = new LinkedHashMap<>(capacity);
    }

    public int get(int key) {
         // write code here
        int value = linkedHashMap.getOrDefault(key, -1);
        if (value != -1) {
            linkedHashMap.remove(key, value);
            linkedHashMap.put(key, value);
        }
        return value;
    }

    public void set(int key, int value) {
         // write code here
        
        // 判断是插入操作还是变更操作
        int op = linkedHashMap.getOrDefault(key, -1);
        
        // 更改操作
        if (op != -1) {
            linkedHashMap.put(key, value);
        }
        
        // 插入操作
        else {
            int sz = linkedHashMap.size();
            // 判断当前容量是否已经达到了上限
            if (sz == capacity) {
                linkedHashMap.remove(linkedHashMap.keySet().toArray()[0]);
                linkedHashMap.put(key, value);
            }
            else {
                linkedHashMap.put(key, value);
            }
        }

    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution solution = new Solution(capacity);
 * int output = solution.get(key);
 * solution.set(key,value);
 */
全部评论
如果原本 linkedhashMap 就有 key,-1 这样的键值对呢
点赞 回复 分享
发布于 2022-04-20 13:22

相关推荐

一天代码十万三:这个学历有中大厂实习也是0面,没办法,斩杀线是这样的
点赞 评论 收藏
分享
在看牛客的社畜很积极:身高体重那一行信息去掉,学校那一行的信息放上面,找半天都没找到你是哪个学校什么专业的
点赞 评论 收藏
分享
用微笑面对困难:加急通知你不合适,也很吗有礼貌了你。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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