From b519d27ddf2123a3edceb43359748fa52a7536b5 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 2 Jun 2024 13:07:15 +0800 Subject: [PATCH] 20240602 Finished --- LeetCodeSharp/Problems/Solution146.cs | 69 +++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 LeetCodeSharp/Problems/Solution146.cs diff --git a/LeetCodeSharp/Problems/Solution146.cs b/LeetCodeSharp/Problems/Solution146.cs new file mode 100644 index 0000000..d06ffce --- /dev/null +++ b/LeetCodeSharp/Problems/Solution146.cs @@ -0,0 +1,69 @@ +// [146] LRU Cache + + +using System.Collections.Generic; + +namespace LeetCodeSharp.Problems146 +{ + // Submission codes start here + public class LRUCache + { + private readonly int _capacity; + private readonly Dictionary>> _map; + private readonly LinkedList> _linkedList = new LinkedList>(); + + public LRUCache(int capacity) + { + _map = new Dictionary>>(); + _capacity = capacity; + } + + public int Get(int key) + { + if (!_map.TryGetValue(key, out var node)) + { + return -1; + } + + _linkedList.Remove(node); + var newNode = new LinkedListNode>(node.Value); + _map[key] = newNode; + _linkedList.AddFirst(newNode); + + return node.Value.Value; + } + + public void Put(int key, int value) + { + if (_map.TryGetValue(key, out var existedNode)) + { + _linkedList.Remove(existedNode); + _map.Remove(key); + } + + var node = new LinkedListNode>(new KeyValuePair(key, value)); + _linkedList.AddFirst(node); + _map.Add(key, node); + + if (_map.Count > _capacity) + { + var last = _linkedList.Last; + + if (last != null) + { + _linkedList.RemoveLast(); + _map.Remove(last.Value.Key); + } + } + } + } + + /** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.Get(key); + * obj.Put(key,value); + */ + + // Submission codes end here +} \ No newline at end of file