Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Library;
- using IntPair = KeyValuePair<int, int>;
- public class LRUCache
- {
- private object _syncRoot =new object();
- private readonly Dictionary<int, LinkedListNode<IntPair>> _dictionary;
- private readonly LinkedList<IntPair> _linkedList;
- private readonly int _boundedCapacity;
- public LRUCache(int boundedCapacity)
- {
- if (boundedCapacity < 0)
- throw new ArgumentOutOfRangeException(nameof(boundedCapacity));
- _dictionary = new(boundedCapacity + 1);
- _linkedList = new();
- _boundedCapacity = boundedCapacity;
- }
- public int Count
- {
- get
- {
- lock (_syncRoot) return _dictionary.Count;
- }
- }
- public int Get(int key)
- {
- int retVal = -1;
- lock (_syncRoot)
- {
- if (_dictionary.TryGetValue(key, out var refNode))
- {
- retVal = refNode.Value.Value;
- if (!ReferenceEquals(refNode, _linkedList.Last))
- {
- _linkedList.Remove(refNode);
- _linkedList.AddLast(refNode);
- }
- }
- }
- return retVal;
- }
- public void Put(int key, int value)
- {
- lock (_syncRoot)
- {
- if (_dictionary.TryGetValue(key, out var refNode ))
- {
- refNode.Value = new IntPair(key, value);
- if (!ReferenceEquals(refNode, _linkedList.Last))
- {
- _linkedList.Remove(refNode);
- _linkedList.AddLast(refNode);
- }
- }
- else
- {
- refNode = new LinkedListNode<IntPair>(new IntPair(key, value));
- _linkedList.AddLast(refNode);
- _dictionary.Add(key,refNode);
- if (_dictionary.Count > _boundedCapacity)
- {
- _ = _dictionary.Remove(_linkedList.First!.Value.Key);
- _linkedList.RemoveFirst();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement