LRU 的C# 實現

首先 先寫點兒感悟吧: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

相關文章
相關標籤/搜索