首页 > 其他 > 详细

【LeetCode】LRU Cache

时间:2014-05-23 09:58:07      阅读:342      评论:0      收藏:0      [点我收藏+]

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

bubuko.com,布布扣
public class LRUCache {
    private int capacity;
    Map<Integer,Integer> map;
    
    public LRUCache(int capacity) {
        this.capacity=capacity;
        map =new LRULinkedHashMap<Integer,Integer>(capacity);
       
    }
    
    public int get(int key) {
        
        if(map.containsKey(key))
            return map.get(key);
        
        return -1;
        
    }
    
    public void set(int key, int value) {
        
        map.put(key, value);
        
    }
}
class LRULinkedHashMap<K,V> extends LinkedHashMap<K,V>{  
    
    private int capacity;  
    private static final long serialVersionUID = 1L;  
   
    LRULinkedHashMap(int capacity){  
        
        super(16,0.75f,true);  
         
        this.capacity=capacity;  
    }  
    
    @Override  
    public boolean removeEldestEntry(Map.Entry<K, V> eldest){   
        
        return size()>capacity;  
    }    
}
bubuko.com,布布扣

借鉴大神的文章 LinkedHashMap

LinkedHashMap默认的元素顺序是put的顺序,但是如果使用带参数的构造函数,那么LinkedHashMap会根据访问顺序来调整内部 顺序。 LinkedHashMap的get()方法除了返回元素之外还可以把被访问的元素放到链表的底端,这样一来每次顶端的元素就是remove的元素。

【LeetCode】LRU Cache,布布扣,bubuko.com

【LeetCode】LRU Cache

原文:http://www.cnblogs.com/yixianyixian/p/3737901.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!