牛客网:NC93 设计LRU缓存结构

package com.company.test.设计LRU缓存结构;

import java.util.*;

/**
 * @author xienl
 * @description 设计LRU缓存结构
 * @date 2022/7/18
 */

public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution(2);
       /* solution.set(1,0);
        solution.set(2,2);
        System.out.println(solution.get(1));
        solution.set(3,3);
        System.out.println(solution.get(2));
        solution.set(4,4);
        System.out.println(solution.get(1));
        System.out.println(solution.get(3));
        System.out.println(solution.get(4));*/
        solution.set(1,1);
        solution.set(2,2);
        solution.set(1,2);
        solution.set(3,3);
        System.out.println(solution.get(1));
    }

    Map<Integer, Node> cache;
    int size;
    int capacity;
    Node head;
    Node tail;

    public Solution(int capacity) {
        // write code here
        cache = new HashMap<>();
        size = 0;
        this.capacity = capacity;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }

    private void remove(Node node){
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }


    private void addHade(Node node){
        node.pre = head;
        node.next = head.next;
        head.next.pre = node;
        head.next = node;
    }

    private void moveToHead(Node node){
        remove(node);
        addHade(node);
    }

    private Node deletetail(){
        Node tail = this.tail.pre;
        remove(tail);
        return tail;
    }

    public int get(int key) {
        // write code here
        Node node = cache.get(key);
        if (node == null){
            return -1;
        }
        moveToHead(node);
        return node.value;
    }

    public void set(int key, int value) {
        // write code here
        Node node = cache.get(key);
        if (node == null){
            Node newNode = new Node(key, value);
            cache.put(key, newNode);
            addHade(newNode);
            size++;
            if (size > capacity){
                Node tail = deletetail();
                cache.remove(tail.key);
                size--;
            }
        } else{
            cache.get(key).value = value;
            moveToHead(node);
        }

    }


    class Node {
        int key;
        int value;
        Node pre;
        Node next;

        public Node (){};

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值