【LeetCode】LRU Cache

设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package letcode;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * 双向链表+HashMap
 *
 * @author zeze
 *
 */
public class LRUCache {
     
     
    public static void main(String[] args) {
 
        /*char key = 0;
        int value = 0;
        LRUCache obj = new LRUCache(capacity);
        int param_1 = obj.get(key);
        obj.put(key, value);*/
 
    }
 
    int capacity;
    Map<Integer, Node> map = new HashMap<Integer, Node>();
    Node head = null;
    Node end = null;
 
 
 
    public LRUCache(int capacity) {
        this.capacity = capacity;
    }
 
    public int get(int key) {
 
        if (map.containsKey(key)) {
            Node temp = map.get(key);
            remove(temp);// 移除节点
            setHead(temp);// 将节点设置为头结点
            return temp.value;
        }
        return -1;
    }
     
    public void put(int key, int value) {
        if (map.containsKey(key)) {// 更新节点
            Node old = map.get(key);
            old.value = value;
            remove(old);
            setHead(old);
        } else {// 插入节点
            Node created = new Node(key, value);
            if (map.size() >= capacity) {
                map.remove(end.key);// HashMap中移除尾节点
                remove(end);// 链表中移除尾节点
                setHead(created);
            } else {
                setHead(created);
            }
            map.put(key, created);
        }
    }
 
    private void setHead(Node n) {
        n.next = head;
        n.pre = null;
        if (head != null) {
            head.pre = n;
        }
        head = n;
        if (end == null)
            end = head;
 
    }
 
    private void remove(Node n) {
        if (n.pre != null)
            n.pre.next = n.next;
        else
            head = n.next;
        if (n.next != null)
            n.next.pre = n.pre;
        else
            end = n.pre;
 
    }
 
     
}
 
class Node {
    int key;
    int value;
    Node pre;
    Node next;
 
    Node(int key, int value) {
        this.key = key;
        this.value = value;
    }
}

  

posted @   陈泽泽  阅读(359)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2015-09-05 php email邮箱正则验证
点击右上角即可分享
微信分享提示