LeetCode LRU Cache (Java实现)

来源:互联网 发布:全军战备值班部队 知乎 编辑:程序博客网 时间:2024/05/20 12:48

LRU Cache

题目要求

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.


参考自两篇博客

http://blog.csdn.net/beiyeqingteng/article/details/7010411

http://gogole.iteye.com/blog/692103

值得一提的是LruCache在Android平台下做图片的缓存非常有效,关于LruCache的官方实现可以参考

http://blog.csdn.net/linghu_java/article/details/8574102

其实 LruCache 也没做什么特别的东西,它不过是给 LinkedHashMap 包了一层而已,真正实现 lru 算法的还是LinkedHashMap


在面试的时候面试官可能不喜欢你用LinkedHashMap实现,所以以下由双链表+hashtable实现

import java.util.Hashtable;public class LRUCache {    int capacity;    int size;    CacheNode first;    CacheNode last;    Hashtable<Integer, CacheNode> nodes = new Hashtable<Integer, CacheNode>();    class CacheNode{        CacheNode prev;        CacheNode next;        int key;        int value;            }        public LRUCache(int capacity) {        this.capacity = capacity;    }        public int get(int key) {        CacheNode node = nodes.get(key);        if (node == null)            return -1;        moveToHead(node);        return node.value;    }        public void set(int key, int value) {        CacheNode node = nodes.get(key);        if (node == null){            if (size >= capacity){                if (last != null){                    nodes.remove(last.key);                }                removeLast();            }else{                ++size;            }            node = new CacheNode();        }        node.key = key;        node.value = value;        moveToHead(node);        nodes.put(key, node);    }    private void removeLast(){        if (last != null){            if (last.prev != null){                last.prev.next = null;            }else{                first = null;            }            last = last.prev;        }    }    private void moveToHead(CacheNode node){        if (node == first)            return;        if (node.prev != null)            node.prev.next = node.next;        if (node.next != null)            node.next.prev = node.prev;        if (last == node)            last = node.prev;         if (first != null){                         first.prev = node;         }         node.next = first;         first = node;         node.prev = null;         if (last == null)             last = first;    }}


0 0