-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution146.cs
57 lines (50 loc) · 1.49 KB
/
Solution146.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
namespace LeetCode.Solutions;
public class Solution146
{
/// <summary>
/// 146. LRU Cache - Medium
/// <a href="https://leetcode.com/problems/lru-cache">See the problem</a>
/// </summary>
public class LRUCache
{
private readonly int _capacity;
private readonly Dictionary<int, LinkedListNode<(int, int)>> _cache;
private readonly LinkedList<(int, int)> _list;
public LRUCache(int capacity)
{
_capacity = capacity;
_cache = new Dictionary<int, LinkedListNode<(int, int)>>();
_list = [];
}
public int Get(int key)
{
if (!_cache.TryGetValue(key, out var node))
{
return -1;
}
_list.Remove(node);
_list.AddFirst(node);
return node.Value.Item2;
}
public void Put(int key, int value)
{
if (_cache.TryGetValue(key, out var node1))
{
_list.Remove(node1);
_list.AddFirst(node1);
node1.Value = (key, value);
}
else
{
if (_cache.Count == _capacity)
{
_cache.Remove(_list.Last!.Value.Item1);
_list.RemoveLast();
}
var node = new LinkedListNode<(int, int)>((key, value));
_cache[key] = node;
_list.AddFirst(node);
}
}
}
}