首先 先写点儿感悟吧:node
原本计划是 晚上回家写的 后来发现仍是没坚持的了 上午花了一个多小时 作了一下这个题目 应该还有提升的空间 的,这个题目是在力扣里面看到的 为何看到这个题目 是由于 我最近在看极客时间里面消息队列有关的课程 有一章讲到了 使用缓存来减小磁盘的IO 里面讲到了这个LRU 置换算法 哎 真的一脸懵逼呀,后来花了2个晚上时间 看了不少文章 涉及到了数据结构 算法 等一系列知识 哪一个时候真的感受心里空洞,毕业X年了 都很差意思说,一些基础 真的 很缺少 感叹 大学 没好好的学,好了 不说了 show code 算法
public class LRUCache { private LinkedList<KeyValuePair<int, int>> linkedList = new LinkedList<KeyValuePair<int, int>>();//双链表 private Dictionary<int, LinkedListNode<KeyValuePair<int, int>>> keyValuePairs = new Dictionary<int, LinkedListNode<KeyValuePair<int, int>>>();//哈希字典 private int _capacity = 0; public LRUCache(int capacity) { keyValuePairs = new Dictionary<int, LinkedListNode<KeyValuePair<int, int>>>(capacity); _capacity = capacity; } public int Get(int key) { if (keyValuePairs.ContainsKey(key) == false) { Console.WriteLine($"输出的值是:-1"); return -1; } var node = keyValuePairs[key].Value; Put(key, node.Value); Console.WriteLine($"输出的值是:{node.Value}"); return node.Value; } public void Put(int key, int val) { LinkedListNode<KeyValuePair<int, int>> newLinkedListNode = new LinkedListNode<KeyValuePair<int, int>>(KeyValuePair.Create(key, val)); if (keyValuePairs.ContainsKey(key)) { linkedList.Remove(keyValuePairs[key]); linkedList.AddFirst(newLinkedListNode); // keyValuePairs.Add(key, newLinkedListNode); keyValuePairs[key] = newLinkedListNode;//更新dic key 中的值 不能用add 会报错 } else { if (_capacity == linkedList.Count) { LinkedListNode<KeyValuePair<int, int>> lastNode = linkedList.Last; linkedList.RemoveLast(); keyValuePairs.Remove(lastNode.Value.Key); } linkedList.AddFirst(newLinkedListNode); keyValuePairs.Add(key, newLinkedListNode); } } }
测试代码缓存
static void Main(string[] args) { LRUCache cache = new LRUCache(2 /* 缓存容量 */ ); cache.Put(1, 1); cache.Put(2, 2); cache.Get(1); // 返回 1 cache.Put(3, 3); // 该操做会使得密钥 2 做废 cache.Get(2); // 返回 -1 (未找到) cache.Put(4, 4); // 该操做会使得密钥 1 做废 cache.Get(1); // 返回 -1 (未找到) cache.Get(3); // 返回 3 cache.Get(4); // 返回 4 }
截图 力扣里面的运行结果:数据结构
从运行结果上面看 这个内存消耗仍是很严重的 后面慢慢研究下怎么去改进:测试
贴上题目的地址:https://leetcode-cn.com/problems/lru-cache/spa
但愿 本身能继续保持 继续加油~ 留给个人时间很少了~code