-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146.lru缓存机制.js
54 lines (50 loc) · 1.04 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
/*
* @lc app=leetcode.cn id=146 lang=javascript
*
* [146] LRU缓存机制
*/
// @lc code=start
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.capacity = capacity;
this._cache = new Map();
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if (this._cache.has(key)) {
const value = this._cache.get(key);
this._cache.delete(key);
this._cache.set(key, value);
return value;
} else {
return -1;
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
if (this._cache.has(key)) {
this._cache.delete(key);
this._cache.set(key, value);
} else {
if (this.capacity === this._cache.size) {
this._cache.delete(this._cache.keys().next().value);
}
this._cache.set(key, value);
}
};
/**
* 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