题解 | #设计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);
 */
查看14道真题和解析