Advertisement
mahldcat

LRUCacheIntPairs.cs

May 8th, 2024
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1.  
  2. namespace Library;
  3. using IntPair = KeyValuePair<int, int>;
  4. public class LRUCache
  5. {
  6. private object _syncRoot =new object();
  7.  
  8. private readonly Dictionary<int, LinkedListNode<IntPair>> _dictionary;
  9. private readonly LinkedList<IntPair> _linkedList;
  10. private readonly int _boundedCapacity;
  11.  
  12. public LRUCache(int boundedCapacity)
  13. {
  14.  
  15. if (boundedCapacity < 0)
  16. throw new ArgumentOutOfRangeException(nameof(boundedCapacity));
  17. _dictionary = new(boundedCapacity + 1);
  18. _linkedList = new();
  19. _boundedCapacity = boundedCapacity;
  20. }
  21.  
  22.  
  23. public int Count
  24. {
  25. get
  26. {
  27. lock (_syncRoot) return _dictionary.Count;
  28. }
  29. }
  30.  
  31. public int Get(int key)
  32. {
  33. int retVal = -1;
  34. lock (_syncRoot)
  35. {
  36. if (_dictionary.TryGetValue(key, out var refNode))
  37. {
  38. retVal = refNode.Value.Value;
  39. if (!ReferenceEquals(refNode, _linkedList.Last))
  40. {
  41. _linkedList.Remove(refNode);
  42. _linkedList.AddLast(refNode);
  43. }
  44. }
  45. }
  46.  
  47. return retVal;
  48. }
  49.  
  50. public void Put(int key, int value)
  51. {
  52. lock (_syncRoot)
  53. {
  54. if (_dictionary.TryGetValue(key, out var refNode ))
  55. {
  56. refNode.Value = new IntPair(key, value);
  57. if (!ReferenceEquals(refNode, _linkedList.Last))
  58. {
  59. _linkedList.Remove(refNode);
  60. _linkedList.AddLast(refNode);
  61. }
  62. }
  63. else
  64. {
  65. refNode = new LinkedListNode<IntPair>(new IntPair(key, value));
  66. _linkedList.AddLast(refNode);
  67. _dictionary.Add(key,refNode);
  68. if (_dictionary.Count > _boundedCapacity)
  69. {
  70. _ = _dictionary.Remove(_linkedList.First!.Value.Key);
  71. _linkedList.RemoveFirst();
  72. }
  73. }
  74. }
  75. }
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement