LRU缓存算法
# LRU缓存算法
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.max = capacity
this.cache = new Map();
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
let flag = this.cache.has(key)
if (flag) {
let value = this.cache.get(key)
this.cache.delete(key)
this.cache.set(key,value)
}
return flag?this.cache.get(key):-1
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
let size = this.cache.size
let max = this.max
if(this.cache.has(key)) {
this.cache.delete(key)
}
this.cache.set(key,value)
while (this.cache.size>max) {
this.cache.delete(this.cache.keys().next().value)
}
};
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
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
更新时间: 3/15/2022, 12:28:01 AM