146. 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.

使用map和双向链表。

public class LRUCache { 

    private class DoublyLinkedListNode {

        public int key;

        public int val;

        public DoublyLinkedListNode pre, next;

        public DoublyLinkedListNode (int k, int v) {

            key = k;

            val = v;

            pre = next = null;

        }

    }

    

    private int capacity, size;

    private Map<Integer, DoublyLinkedListNode> map;

    private DoublyLinkedListNode head, tail;

    

    public LRUCache(int capacity) {

        this.capacity = capacity;

        size = 0;

        map = new HashMap<>(capacity);

    }

    

    private void addToHead(DoublyLinkedListNode node) {

        node.pre = null;

        node.next = head;

        if (head != null) {

            head.pre = node;

        }

        head = node;

        if (tail == null) {

            tail = head;

        }

    }

    

    private void remove(DoublyLinkedListNode node) {

        DoublyLinkedListNode pre = node.pre;

        DoublyLinkedListNode post = node.next;

        if (pre == null) {

            head = post;

        } else {

            pre.next = post;

        }

        if (post == null) {

            tail = pre;

        } else {

            post.pre = pre;

        }

    }

    

    public int get(int key) {

        if (map.containsKey(key)) {

            DoublyLinkedListNode node = map.get(key);

            remove(node);

            addToHead(node);

            return node.val;

        }

        return -1;

    }

    

    public void set(int key, int value) {

        if (map.containsKey(key)) {

            DoublyLinkedListNode node = map.get(key);

            node.val = value;

            remove(node);

            addToHead(node);

        } else {

            DoublyLinkedListNode node = new DoublyLinkedListNode(key, value);

            if (size < capacity) {

                map.put(key, node);

                addToHead(node);

                size ++;

            } else {

                map.remove(tail.key);

                tail = tail.pre;

                if (tail != null) {

                    tail.next = null;

                }

                addToHead(node);

                map.put(key, node);

            }

        }

    }

}

posted on 2015-04-16 05:22  shini  阅读(153)  评论(0编辑  收藏  举报

导航