-
Notifications
You must be signed in to change notification settings - Fork 931
/
Copy pathlru-cache-2.js
72 lines (59 loc) · 1.37 KB
/
lru-cache-2.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
/**
* Least Recently Used (LRU) cache.
* Map + (Hash)Set: O(1)
* @param {number} capacity - Number of items to hold.
*/
var LRUCache = function(capacity) {
this.capacity = capacity || 2;
this.map = new Map();
this.set = new Set();
this.size = 0;
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if (!this.map.has(key)) return -1;
// move to top
this.set.delete(key);
this.set.add(key);
return this.map.get(key);
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
this.map.set(key, value);
// move to top
this.set.delete(key);
this.set.add(key);
if (this.set.size > this.capacity) {
const leastUsedKey = this.set.values().next().value;
this.map.delete(leastUsedKey);
this.set.delete(leastUsedKey);
}
this.size = this.map.size;
};
/**
* 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)
*/
/*
Implement a hashMap cache with a given capacity that once reach deletes the least used element and store the new one.
---
c = new LRUCache(2);
c.put(1,1);
c.put(2,2);
c.put(3,3); // deletes key 1
c = new LRUCache(2);
c.put(1,1);
c.put(2,2);
c.get(1);
c.put(3,3); // deletes key 2
*/
module.exports = LRUCache;