-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
88 lines (72 loc) · 2.13 KB
/
Copy pathLRUCache.java
File metadata and controls
88 lines (72 loc) · 2.13 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
package leetcode.hard.page1;
import java.util.HashMap;
import java.util.Map;
public class LRUCache {
ListNode cacheListHead;
ListNode cacheListTail;
Map<Integer, Integer> cache = new HashMap<>();
int count = 0;
int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (count == 0 || !cache.containsKey(key)) return -1;
moveToHead(key);
return cache.get(cacheListHead.val);
}
public void put(int key, int value) {
if (!cache.containsKey(key)) {
if (count < capacity) {
// the max count is equals to capacity
count++;
ListNode node = new ListNode(key);
if (cacheListHead == null) {
cacheListHead = node;
cacheListTail = node;
} else {
node.next = cacheListHead;
cacheListHead = node;
}
} else {
cache.remove(cacheListTail.val);
ListNode newNode = new ListNode(key);
newNode.next = cacheListHead;
cacheListHead = newNode;
ListNode tmpNode = cacheListHead;
while (tmpNode.next != cacheListTail) {
tmpNode = tmpNode.next;
}
tmpNode.next = null;
cacheListTail = tmpNode;
}
} else {
moveToHead(key);
}
cache.put(key, value);
}
private void moveToHead(int key) {
if (cacheListHead.val == key) {
return;
}
ListNode p = cacheListHead;
ListNode q = p.next;
while (q.val != key) {
p = q;
q = p.next;
}
// move q to head
p.next = q.next;
q.next = cacheListHead;
cacheListHead = q;
if (p.next == null) cacheListTail = p;
}
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
next = null;
}
}
}