-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
108 lines (81 loc) · 1.68 KB
/
LRUCache.java
File metadata and controls
108 lines (81 loc) · 1.68 KB
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
import java.util.*;
public class LRUCache {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private int m_capacity;
private Node m_head;
private Map<Integer, Node> m_map;
public LRUCache(int capacity) {
m_capacity = capacity;
m_head = new Node(0,0);
m_map = new HashMap<Integer, Node>();
}
public int get(int key) {
if(m_map.containsKey(key))
{
Node n = m_map.get(key);
Node prev = n.prev;
Node next = n.next;
prev.next = next;
next.prev = prev;
Node hNext = m_head.next;
m_head.next = n;
hNext.prev = n;
n.prev = m_head;
n.next = hNext;
return n.value;
}
else
{
return -1;
}
}
public void set(int key, int value) {
Node n;
if(m_map.containsKey(key))
{
n = m_map.get(key);
n.value = value;
Node prev = n.prev;
Node next = n.next;
prev.next = next;
next.prev = prev;
}
else
{
n = new Node(key, value);
m_map.put(key, n);
}
Node hNext = m_head.next;
m_head.next = n;
hNext.prev = n;
n.prev = m_head;
n.next = hNext;
if(m_map.size() > m_capacity)
{
Node hPrev = m_head.prev;
int k = hPrev.key;
hPrev.prev.next = m_head;
m_head.prev = hPrev.prev;
m_map.remove(k);
}
}
class Node
{
int key;
int value;
public Node prev;
public Node next;
Node(int k, int v)
{
key = k;
value = v;
prev = this;
next = this;
}
}
}