-
Notifications
You must be signed in to change notification settings - Fork 4
/
146.zy445566.js
45 lines (41 loc) · 940 Bytes
/
146.zy445566.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
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.capacity = capacity;
this.lruData = [];
this.lruMap = {};
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
let index = this.lruData.indexOf(key);
if (index>-1) {
this.lruData.splice(index,1);
this.lruData.push(key);
return this.lruMap[key];
} else {
return -1;
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
let index = this.lruData.indexOf(key);
if (index>-1) {
this.lruMap[key] = value;
this.get(key);
} else {
if (this.lruData.length>=this.capacity) {
let delKey = this.lruData.shift();
delete this.lruMap[delKey];
}
this.lruData.push(key)
this.lruMap[key] = value;
}
};