LRU Cache

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.

思路:

  双向链表

我的代码:

public class LRUCache {
    
    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.head = new Node(-1, -1);
        this.tail = new Node(-1, -1);
        head.next = tail;
        tail.pre = head;
    }
    
    public int get(int key) {
        if(!hm.containsKey(key))    return -1;
        Node node = hm.get(key);
        //remove current
        node.pre.next = node.next;
        node.next.pre = node.pre;
        moveTotail(node);
        return node.val;
    }
    
    public void set(int key, int value) {
        if(get(key) != -1)
        {
            hm.get(key).val = value;
            return;
        }
        if(hm.size() == capacity)
        {
            hm.remove(head.next.key);
            head.next = head.next.next;
            head.next.pre = head;
        }
        Node node = new Node(key,value);
        hm.put(key,node);
        moveTotail(node);
    }
    public void moveTotail(Node node){
        node.pre = tail.pre;
        node.next = tail;
        tail.pre.next = node;
        tail.pre = node;
    }
    private Node head; 
    private Node tail;
    private int capacity;
    private HashMap<Integer,Node> hm = new HashMap<Integer,Node>();
    private class Node{
        Node pre;
        Node next;
        int key;
        int val;
        public Node(int key, int val)
        {
            this.key = key;
            this.val = val;
        }
    }
}
View Code

学习之处:

  • 在做这道题的时候,一下子就想到双向链表了,由于自己觉得简单,就边看答案边做的,差评!!!
  • 这道题有点眼高手低,以后不能这样!其实好长时间才AC的

posted on 2015-03-31 20:19  zhouzhou0615  阅读(111)  评论(0编辑  收藏  举报

导航