• 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的
  • 相关阅读:
    VA插件突然不能使用,彈出“the security key for....”
    【WIN10】Segoe MDL2 Assets
    【WIN10】WIN2D——圖層
    【WIN10】WIN2D——圖像處理
    【WIN10】WIN2D——繪製文字
    【WIN10】WIN2D——基本圖形的繪製
    為你的文件夾添加“使用CMD命令打開”菜單
    【WIN10】移植opencc到WIN10-UWP,實現自己的繁簡轉換工具
    【WIN10】判斷程序運行在哪個平台
    【WIN10】使用VS生成appx安裝包,並安裝測試
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4381909.html
Copyright © 2020-2023  润新知