-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path146.LRUCache.cs
111 lines (103 loc) · 2.35 KB
/
146.LRUCache.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
99
100
101
102
103
104
105
106
107
108
109
110
111
// https://leetcode.com/problems/lru-cache/
using System.Collections.Generic;
public class LRUCache
{
class Node
{
public Node Prev;
public Node Next;
public int Key;
public int Value;
}
private Node _head;
private Node _tail;
private Dictionary<int, Node> keyMap;
private readonly int _capacity;
public LRUCache(int capacity)
{
_capacity = capacity;
keyMap = new Dictionary<int, Node>();
}
public int Get(int key)
{
Node node;
if (keyMap.TryGetValue(key, out node))
{
MoveToHead(node);
return node.Value;
}
return -1;
}
public void Put(int key, int value)
{
Node node;
if (keyMap.TryGetValue(key, out node))
{
MoveToHead(node);
node.Value = value;
}
else
{
if (keyMap.Count == _capacity)
{
if (_capacity > 0)
{
keyMap.Remove(_tail.Key);
RemoveTail();
}
else
{
return;
}
}
node = new Node() { Key = key, Value = value };
keyMap.Add(key, node);
MoveToHead(node);
}
}
private void MoveToHead(Node node)
{
if (_head != node)
{
if (_head == null)
{
_head = node;
_tail = node;
}
else
{
if (_tail == node)
{
_tail = node.Prev;
}
if (node.Next != null)
{
node.Next.Prev = node.Prev;
}
if (node.Prev != null)
{
node.Prev.Next = node.Next;
}
node.Next = _head;
_head.Prev = node;
_head = node;
}
}
}
private void RemoveTail()
{
if (_tail != null)
{
if (_tail.Prev == null)
{
_head = null;
_tail = null;
}
else
{
_tail = _tail.Prev;
_tail.Next = null;
}
}
}
}