-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146.lru缓存机制.js
106 lines (90 loc) · 2.32 KB
/
146.lru缓存机制.js
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
/*
* @lc app=leetcode.cn id=146 lang=javascript
*
* [146] LRU缓存机制
*/
// @lc code=start
var LRUCache = function (capacity) {
this.size = 0; // 缓存的数目
this.capacity = capacity; // 缓存的容量
this.hashTable = new Map();
this.head = new DLinkedNode();
this.tail = new DLinkedNode();
this.head.next = this.tail;
this.tail.prev = this.head;
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function (key) {
if (!this.hashTable.has(key)) return -1;
let node = this.hashTable.get(key);
this.moveToHead(node);
return node.value;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function (key, value) {
let node = this.hashTable.get(key);
if (!node) {
let newNode = new DLinkedNode(key, value);
// 将节点添加到双向链表的头部
this.addToHead(newNode);
if (this.size > this.capacity) {
// 移除链表中最后一个值,将值从Hash表中移除
this.pop();
}
} else {
// 更新value
node.value = value;
this.moveToHead(node);
}
};
// 删除指定元素
LRUCache.prototype.remove = function (node) {
node.next.prev = node.prev;
node.prev.next = node.next;
// 删除元素,把hash表中也删除
this.hashTable.delete(node.key);
this.size--;
};
// 删除最后一个元素
LRUCache.prototype.pop = function () {
let tailNode = this.tail.prev;
this.remove(tailNode);
return tailNode;
};
// 添加到头部
LRUCache.prototype.addToHead = function (node) {
node.prev = this.head;
node.next = this.head.next;
this.head.next.prev = node;
this.head.next = node;
// 添加到头部后,添加到hash中去。
this.hashTable.set(node.key, node);
this.size++
};
// 移动到头部
LRUCache.prototype.moveToHead = function (node) {
// 先删除后添加
this.remove(node);
this.addToHead(node);
};
// 双向链表的构造函数
var DLinkedNode = function (key, value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
// @lc code=end