zoukankan      html  css  js  c++  java
  • 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的
  • 相关阅读:
    python之turtle画蚊香
    day08:多表查询
    day07:内置函数
    day06:基础查询
    day05:Navicat 图形化客户端的基本使用
    day04:MySQL数据库表的基本命令
    day03:MySQL数据库的使用
    day02:MySQL数据库的安装
    day01:数据库和SQL概述
    51单片机学习笔记(清翔版)(13)——LED点阵、74HC595
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4381909.html
Copyright © 2011-2022 走看看