LRU 的C# 实现

首先 先写点儿感悟吧:

本来计划是 晚上回家写的  后来发现还是没坚持的了  上午花了一个多小时  做了一下这个题目  应该还有提高的空间 的,这个题目是在力扣里面看到的  为什么看到这个题目 是因为 我最近在看极客时间里面消息队列有关的课程 有一章讲到了 使用缓存来减少磁盘的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/

希望 自己能继续保持  继续加油~ 留给我的时间不多了~

 

posted @ 2019-10-25 17:10  burg-xun  阅读(639)  评论(0编辑  收藏  举报