算法:手动实现LRUCache

一、算法代码 

import java.util.*;

/**
 * 手动实现LRUCache
 */
@SuppressWarnings("all")
class LRUCache {

    /**
     * map中的键为LRUCache的key,值为LRUCache中的key和value组成的Node节点
     */
    private HashMap map;

    /**
     * 存储LRUCache中的key和value组成的Node节点
     */
    private LinkedList linkedList;

    private int capacity;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        map = new HashMap<>();
        linkedList = new LinkedList<>();
    }

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

    public void put(int key, int value) {
        Node node = map.get(key);
        if (node == null) {
            Node newNode = new Node(key, value);
            map.put(key, newNode);
            linkedList.add(newNode);
            if (linkedList.size() > capacity) {
                Node poll = linkedList.poll();
                map.remove(poll.key);
            }
        } else {
            node.value = value;
            moveToHead(node);
        }
    }

    public void moveToHead(Node node) {
        linkedList.remove(node);
        linkedList.add(node);
    }

    class Node {
        public Integer key;
        public Integer value;

        public Node(Integer key, Integer value) {
            this.key = key;
            this.value = value;
        }
    }

    public static void main(String[] args) {
        LRUCache lRUCache = new LRUCache(2);
        System.out.println(lRUCache.get(2));
        lRUCache.put(2, 6);
        System.out.println(lRUCache.get(1));
        lRUCache.put(1, 5);
        lRUCache.put(1, 2);
        System.out.println(lRUCache.get(1));
        System.out.println(lRUCache.get(2));
    }
}

你可能感兴趣的:(算法,开发语言,java)