134. lru cache

code

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

// get, move the node to tail
// set add the node to tail, delete head
public class {
private class ListNode {
int key;
int val;
ListNode prev;
ListNode next;
public ListNode(int key, int val) {
this.key = key;// need key and val
this.val = val;
}
}


private HashMap<Integer, ListNode> map; // key, node
private int capacity;
private ListNode head;
private ListNode tail;
/*
* @param capacity: An integer
*/public (int capacity) {
// do intialization if necessary
this.capacity = capacity;
map = new HashMap<Integer, ListNode>();
head = new ListNode(-1, -1);//建立挡板可以避免很多没有头尾的情况!!!
tail = new ListNode(-1, -1);
head.next = tail;
tail.prev = head;
}

/*
* @param key: An integer
* @return: An integer
*/
public int get(int key) {
// write your code here
if (!map.containsKey(key)) {
return -1;
}
ListNode curt = map.get(key);

moveToTail(curt);
return curt.val;

}
private void moveToTail(ListNode node) {

node.prev.next = node.next;
node.next.prev = node.prev;
node.prev = tail.prev;
node.next = tail;
node.prev.next = node;
tail.prev = node;

}

/*
* @param key: An integer
* @param value: An integer
* @return: nothing
*/
public void set(int key, int value) {
// write your code here
if (get(key) != -1) { // 如果重复,移到后面,直接return
map.get(key).val = value;
return;
}

ListNode curt = new ListNode(key, value);
if (map.size() >= capacity) {
map.remove(head.next.key);
head.next = head.next.next;
head.next.prev = head;
}

map.put(key, curt);
curt.prev = tail.prev;
curt.next = tail;
curt.prev.next = curt;
tail.prev = curt;


}
}