Skip to content

Commit eee8d7c

Browse files
Create 146-LRU-Cache.cs
File(s) Modified: 146-LRU-Cache.cs Language(s) Used: csharp Submission URL: https://leetcode.com/submissions/detail/773840490/
1 parent a0c6dd2 commit eee8d7c

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

Diff for: csharp/146-LRU-Cache.cs

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
public class Node
2+
{
3+
public int val;
4+
public int key;
5+
public Node prev;
6+
public Node next;
7+
8+
public Node(int key, int val)
9+
{
10+
this.key = key;
11+
this.val = val;
12+
prev = null;
13+
next = null;
14+
}
15+
}
16+
17+
public class LRUCache
18+
{
19+
private Dictionary<int, Node> keyValue = new();
20+
private int _capacity;
21+
private Node left;
22+
private Node right;
23+
24+
//T: O(1), S: O(Capacity)
25+
public LRUCache(int capacity)
26+
{
27+
_capacity = capacity;
28+
left = new Node(0, 0);
29+
right = new Node(0, 0);
30+
// left : LRU, right : MRU (Most recently used)
31+
left.next = right;
32+
right.prev = left;
33+
}
34+
35+
//Remove from list
36+
private void remove(Node node)
37+
{
38+
var prev = node.prev;
39+
var next = node.next;
40+
41+
prev.next = next;
42+
next.prev = prev;
43+
}
44+
45+
// Insert at right
46+
private void insert(Node node)
47+
{
48+
var next = right;
49+
var prev = right.prev;
50+
51+
node.next = next;
52+
next.prev = node;
53+
prev.next = node;
54+
node.prev = prev;
55+
56+
}
57+
58+
public int Get(int key)
59+
{
60+
if (!keyValue.ContainsKey(key))
61+
return -1;
62+
// we need to update this to be MRU
63+
var node = keyValue[key];
64+
remove(node);
65+
insert(node);
66+
return node.val;
67+
}
68+
69+
public void Put(int key, int value)
70+
{
71+
if (keyValue.ContainsKey(key))
72+
{
73+
var node = keyValue[key];
74+
keyValue.Remove(key);
75+
remove(node);
76+
}
77+
78+
var newNode = new Node(key, value);
79+
keyValue.Add(key, newNode);
80+
insert(newNode);
81+
82+
if (keyValue.Count > _capacity)
83+
{
84+
// remove from the list and delete the LRU from dictionary
85+
var lru = left.next;
86+
remove(lru);
87+
keyValue.Remove(lru.key);
88+
}
89+
90+
}
91+
}
92+
93+
/**
94+
* Your LRUCache object will be instantiated and called as such:
95+
* LRUCache obj = new LRUCache(capacity);
96+
* int param_1 = obj.Get(key);
97+
* obj.Put(key,value);
98+
*/

0 commit comments

Comments
 (0)