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

设计LRU缓存结构

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

使用匿名内部类,重写removeEldestEntry(),LinkedHashMap的方式实现一个LRU缓存结构

import java.util.*;


public class Solution  {
    public  LinkedHashMap<Integer,Integer> linkedHashMap;
    public Solution(int capacity) {
         // write code here
       linkedHashMap = new LinkedHashMap<Integer,Integer>(capacity, 0.75f, true) {
            private static final long serialVersionUID = -6383651257854861378L;

            @Override
            protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
                return size() > capacity;
            }
        };     
    }

    public int get(int key) {
         // write code here
        if(linkedHashMap.containsKey(key)){
            return (int) linkedHashMap.get(key);
        } else {
            return -1;
        }    
    }

    public void set(int key, int value) {
         // write code here
          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);
 */
全部评论

相关推荐

09-13 18:00
武汉大学 Java
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

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