Skip to content

Commit 21c8b1e

Browse files
authored
Update 146-lru-cache.js
1 parent 6a9a8f5 commit 21c8b1e

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

146-lru-cache.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,50 @@ LRUCache.prototype.put = function(key, value) {
8080
* var param_1 = obj.get(key)
8181
* obj.put(key,value)
8282
*/
83+
84+
// another
85+
86+
/**
87+
* @param {number} capacity
88+
*/
89+
const LRUCache = function(capacity) {
90+
this.m = new Map()
91+
this.l = capacity
92+
};
93+
94+
/**
95+
* @param {number} key
96+
* @return {number}
97+
*/
98+
LRUCache.prototype.get = function(key) {
99+
if(!this.m.has(key)) return -1
100+
const v = this.m.get(key)
101+
this.m.delete(key)
102+
this.m.set(key, v)
103+
return v
104+
};
105+
106+
/**
107+
* @param {number} key
108+
* @param {number} value
109+
* @return {void}
110+
*/
111+
LRUCache.prototype.put = function(key, value) {
112+
if(this.m.has(key)) {
113+
this.m.delete(key)
114+
this.m.set(key, value)
115+
} else {
116+
if(this.m.size >= this.l) {
117+
const k = this.m.keys().next().value
118+
this.m.delete(k)
119+
}
120+
this.m.set(key, value)
121+
}
122+
};
123+
124+
/**
125+
* Your LRUCache object will be instantiated and called as such:
126+
* var obj = new LRUCache(capacity)
127+
* var param_1 = obj.get(key)
128+
* obj.put(key,value)
129+
*/

0 commit comments

Comments
 (0)