LeetCode146. LRU缓存机制

题目来源:

https://leetcode-cn.com/problems/lru-cache/submissions/

题目描述:

LeetCode146. LRU缓存机制_第1张图片

代码如下:

方式一:LRU实现手段就是哈希表+链表,而LinkedHashMap正好存在该特性。因此利用LinkedHashMap即可实现该功能。

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

class LRUCache extends LinkedHashMap {
    private int capacity;

    public LRUCache(int capacity) {
        super(capacity, 0.75F, true);
        this.capacity = capacity;
    }

    public int get(int key) {
        //返回结点,如果不存在返回-1。并且还会将返回的结点插入到链表最后
        return super.getOrDefault(key, -1);
    }

    public void put(int key, int value) {
        //put最后会调用到removeEldestEntry,如果该方法返回true,会删除链表头结点
        super.put(key, value);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > capacity;
    }
}

方式二:在HashMap的基础上自己手动维护了链表。

package study01;

import java.util.HashMap;
import java.util.Map;

class LRUCache {
    // 双链表节点
    class Node {
        int key;
        int val;
        Node prev;
        Node next;
    }
    private int capacity;
    private Node first;
    private Node last;
    private Map map;
    public LRUCache(int capacity) {
        this.capacity = capacity;
        map = new HashMap<>(capacity);
    }
    public int get(int key) {
        Node node = map.get(key);
        if (node == null) {
            return -1;
        }
        moveToHead(node);
        return node.val;
    }
    public void put(int key, int value) {
        Node node = map.get(key);
        if (node == null) {
            node = new Node();
            node.key = key;
            node.val = value;
            if (map.size() == capacity) {
                removeLast();
            }
            addToHead(node);
            map.put(key, node);
        } else {
            node.val = value;
            moveToHead(node);
        }
    }
    private void moveToHead(Node node) {
        if (node == first) {
            return;
        } else if (node == last) {
            last.prev.next = null;
            last = last.prev;
        } else {
            node.prev.next = node.next;
            node.next.prev = node.prev;
        }
        node.prev = first.prev;
        node.next = first;
        first.prev = node;
        first = node;
    }
    private void addToHead(Node node) {
        if (map.isEmpty()) {
            first = node;
            last = node;
        } else {
            node.next = first;
            first.prev = node;
            first = node;
        }
    }
    private void removeLast() {
        map.remove(last.key);
        Node prevNode = last.prev;
        if (prevNode != null) {
            prevNode.next = null;
            last = prevNode;
        }
    }
}

 

你可能感兴趣的:(LeetCode146. LRU缓存机制)