forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0146-lru-cache.cs
98 lines (84 loc) · 2.01 KB
/
0146-lru-cache.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
public class Node
{
public int val;
public int key;
public Node prev;
public Node next;
public Node(int key, int val)
{
this.key = key;
this.val = val;
prev = null;
next = null;
}
}
public class LRUCache
{
private Dictionary<int, Node> keyValue = new();
private int _capacity;
private Node left;
private Node right;
//T: O(1), S: O(Capacity)
public LRUCache(int capacity)
{
_capacity = capacity;
left = new Node(0, 0);
right = new Node(0, 0);
// left : LRU, right : MRU (Most recently used)
left.next = right;
right.prev = left;
}
//Remove from list
private void remove(Node node)
{
var prev = node.prev;
var next = node.next;
prev.next = next;
next.prev = prev;
}
// Insert at right
private void insert(Node node)
{
var next = right;
var prev = right.prev;
node.next = next;
next.prev = node;
prev.next = node;
node.prev = prev;
}
public int Get(int key)
{
if (!keyValue.ContainsKey(key))
return -1;
// we need to update this to be MRU
var node = keyValue[key];
remove(node);
insert(node);
return node.val;
}
public void Put(int key, int value)
{
if (keyValue.ContainsKey(key))
{
var node = keyValue[key];
keyValue.Remove(key);
remove(node);
}
var newNode = new Node(key, value);
keyValue.Add(key, newNode);
insert(newNode);
if (keyValue.Count > _capacity)
{
// remove from the list and delete the LRU from dictionary
var lru = left.next;
remove(lru);
keyValue.Remove(lru.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);
*/