lc146.java 2.3 KB
Newer Older
L
liu13 已提交
1 2 3 4 5 6 7 8
package code;
/*
 * 146. LRU Cache
 * 题意:首先理解LRU思想,最久未被访问过的,最先被替换
 * 难度:Hard
 * 分类:Design
 * 思路:hashmap + 双向链表。hashmap实现了O(1)的get,双向链表实现O(1)的put
 * Tips:能想到双向链表,就不难了
L
liu13 已提交
9
 *      lc380
L
liu13 已提交
10 11 12 13
 */
import java.util.HashMap;

public class lc146 {
L
liu13 已提交
14
    class Node {    //定义一个Node类
L
liu13 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27
        int key;
        int value;
        Node pre;
        Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    public class LRUCache {

        HashMap<Integer, Node> map;
L
liu13 已提交
28 29
        int capicity, count;    //最大容量,当前容量
        Node head, tail;    //头节点,尾节点
L
liu13 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42

        public LRUCache(int capacity) {
            this.capicity = capacity;
            map = new HashMap<>();
            head = new Node(0, 0);
            tail = new Node(0, 0);
            head.next = tail;
            tail.pre = head;
            head.pre = null;
            tail.next = null;
            count = 0;
        }

L
liu13 已提交
43
        public void deleteNode(Node node) { //两个方法
L
liu13 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
            node.pre.next = node.next;
            node.next.pre = node.pre;
        }

        public void addToHead(Node node) {
            node.next = head.next;
            node.next.pre = node;
            node.pre = head;
            head.next = node;
        }

        public int get(int key) {
            if (map.get(key) != null) {
                Node node = map.get(key);
                int result = node.value;
                deleteNode(node);
                addToHead(node);
                return result;
            }
            return -1;
        }

        public void put(int key, int value) {
            if (map.get(key) != null) {
                Node node = map.get(key);
                node.value = value;
                deleteNode(node);
                addToHead(node);
            } else {
                Node node = new Node(key, value);
                map.put(key, node);
                if (count < capicity) {
                    count++;
                    addToHead(node);
                } else {
                    map.remove(tail.pre.key);
                    deleteNode(tail.pre);
                    addToHead(node);
                }
            }
        }
    }
}