forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode_LRUCache.java
More file actions
63 lines (55 loc) · 1.42 KB
/
Leetcode_LRUCache.java
File metadata and controls
63 lines (55 loc) · 1.42 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
class LRUCache {
Node head = new Node(0,0);
Node tail = new Node(0,0);
HashMap<Integer,Node> cache;
int capacity;
public LRUCache(int capacity) {
head.next = tail;
tail.prev = head;
cache = new HashMap<>();
this.capacity = capacity;
}
public int get(int key) {
if(cache.containsKey(key)){
Node curNode = cache.get(key);
remove(curNode);
insert(curNode);
return curNode.value;
}else{
return -1;
}
}
public void put(int key, int value) {
if(cache.containsKey(key)){
remove(cache.get(key));
}
if(cache.size() == capacity){
remove(tail.prev);
}
Node newNode = new Node(key,value);
insert(newNode);
}
private void remove(Node node){
cache.remove(node.key);
Node prevNode = node.prev;
Node nextNode = node.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
}
private void insert(Node node){
Node prevMostRUN = head.next;
head.next = node;
node.next = prevMostRUN;
node.prev = head;
prevMostRUN.prev = node;
cache.put(node.key,node);
}
}
class Node{
int key, value;
Node next, prev;
Node(int key, int value){
this.key = key;
this.value = value;
}
}