文章目录
  1. 1. 未被Accepted的代码
  2. 2. 双向链表+HashMap
  3. 3. LinkedHashMap

【题目】: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.

这是leetcode上的一道题目,最开始我是用数组实现的,然后没有被Accepted,提示我time limit exceeded,是当容量特别大的时候,不满足时间上的要求了。

未被Accepted的代码

public class LRUCache {
    private int max_size;
    private int index;
    private Entry[] entries;

    public LRUCache(int capacity) {
        this.max_size = capacity;
        index = -1;
        entries = new Entry[this.max_size];
    }

    public int get(int key) {
        for (int i=0; i<=index; i++) {
            if (entries[i].key == key) {
                return entries[i].value;
            }
        }
        return -1;
    }

    public void set(int key, int value) {
        int tem = -1;
        for (int i=0; i<=index; i++) {
            if (entries[i].key == key) {
                tem = i;
                break;
            }
        }

        if (tem != -1) {
            entries[tem].value = value;
            entries[tem].time = 0;
        } else {
            Entry entry = new Entry(key, value, 0);
            if (index >= max_size-1) {
                tem = 0;
                for (int i=0; i<=index; i++) {
                    if (entries[i].time > entries[tem].time) {
                        tem = i;
                    }
                }

                entries[tem] = entry;
            } else {
                entries[++index] = entry;
            }
        }

        for (int i=0; i<=index; i++) {
            entries[i].time++;
        }



    }

    class Entry {
        int key;
        int value;
        int time;

        Entry(int key, int value, int time) {
            this.key = key;
            this.value = value;
            this.time = time;
        }
    }
}

整体思路是加一个时间的标志位。

双向链表+HashMap

双向链表用于存储数据结点,并且它是按照结点最近被使用的时间来存储的。 如果一个结点被访问了, 我们有理由相信它在接下来的一段时间被访问的概率要大于其它结点。于是, 我们把它放到双向链表的头部。当我们往双向链表里插入一个结点, 我们也有可能很快就会使用到它,同样把它插入到头部。 我们使用这种方式不断地调整着双向链表,链表尾部的结点自然也就是最近一段时间, 最久没有使用到的结点。那么,当我们的Cache满了, 需要替换掉的就是双向链表中最后的那个结点。

import java.util.HashMap;

public class LRUCache {
    private HashMap<Integer, DoubleLinkedListNode> map 
        = new HashMap<Integer, DoubleLinkedListNode>();
    private DoubleLinkedListNode head;
    private DoubleLinkedListNode end;
    private int capacity;
    private int len;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        len = 0;
    }

    public int get(int key) {
        if (map.containsKey(key)) {
            DoubleLinkedListNode latest = map.get(key);
            removeNode(latest);
            setHead(latest);
            return latest.val;
        } else {
            return -1;
        }
    }

    public void removeNode(DoubleLinkedListNode node) {
        DoubleLinkedListNode cur = node;
        DoubleLinkedListNode pre = cur.pre;
        DoubleLinkedListNode post = cur.next;

        if (pre != null) {
            pre.next = post;
        } else {
            head = post;
        }

        if (post != null) {
            post.pre = pre;
        } else {
            end = pre;
        }
    }

    public void setHead(DoubleLinkedListNode node) {
        node.next = head;
        node.pre = null;
        if (head != null) {
            head.pre = node;
        }

        head = node;
        if (end == null) {
            end = node;
        }
    }

    public void set(int key, int value) {
        if (map.containsKey(key)) {
            DoubleLinkedListNode oldNode = map.get(key);
            oldNode.val = value;
            removeNode(oldNode);
            setHead(oldNode);
        } else {
            DoubleLinkedListNode newNode = 
                new DoubleLinkedListNode(key, value);
            if (len < capacity) {
                setHead(newNode);
                map.put(key, newNode);
                len++;
            } else {
                map.remove(end.key);
                end = end.pre;
                if (end != null) {
                    end.next = null;
                }

                setHead(newNode);
                map.put(key, newNode);
            }
        }
    }
}

class DoubleLinkedListNode {
    public int val;
    public int key;
    public DoubleLinkedListNode pre;
    public DoubleLinkedListNode next;

    public DoubleLinkedListNode(int key, int value) {
        val = value;
        this.key = key;
    }
}

LinkedHashMap

LinkedHashMap恰好是通过双向链表实现的java集合类,它的一大特点是,以当某个位置被命中,它就会通过调整链表的指向,将该位置调整到头位置,新加入的内容直接放在链表头,如此一来,最近被命中的内容就向链表头移动,需要替换时,链表最后的位置就是最近最少使用的位置。

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache extends LinkedHashMap<Integer, Integer> {
    private int capacity;

    public LRUCache(int capacity) {
        super(16, 0.75f, true);
        this.capacity = capacity;
    }
    //重写父类get,为null时范围-1
    public Integer get(Object key) {
        Integer v = super.get(key);
        if (v != null)
            return v;
        else
            return -1;
    }
    //重写父类方法,当超过缓存容量时,就删除最老的
    public boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        return size() > capacity;
    }

    public void set(int key, int value) {
        super.put(key, value);
    }
}
文章目录
  1. 1. 未被Accepted的代码
  2. 2. 双向链表+HashMap
  3. 3. LinkedHashMap