|
| 1 | +class Node { |
| 2 | + constructor(key, val) { |
| 3 | + this.val = val; |
| 4 | + this.key = key; |
| 5 | + this.next = this.pre = null; |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +const LRUCache = function(capacity) { |
| 10 | + this.capacity = capacity; |
| 11 | + this.count = 0; |
| 12 | + this.start = new Node(-1, -1); |
| 13 | + this.end = new Node(-1, -1); |
| 14 | + this.start.next = this.end; |
| 15 | + this.end.pre = this.start; |
| 16 | + this.map = {}; |
| 17 | +}; |
| 18 | + |
| 19 | +// insert node into the next of the start |
| 20 | +const insertAfter = function(start, node) { |
| 21 | + let next = start.next; |
| 22 | + start.next = node; |
| 23 | + node.pre = start; |
| 24 | + node.next = next; |
| 25 | + next.pre = node; |
| 26 | +}; |
| 27 | + |
| 28 | +const detach = function(node) { |
| 29 | + let pre = node.pre, |
| 30 | + next = node.next; |
| 31 | + pre.next = next; |
| 32 | + next.pre = pre; |
| 33 | + node.next = node.pre = null; |
| 34 | +}; |
| 35 | + |
| 36 | +/** |
| 37 | + * @param {number} key |
| 38 | + * @return {number} |
| 39 | + */ |
| 40 | +LRUCache.prototype.get = function(key) { |
| 41 | + let node = this.map[key]; |
| 42 | + if (node != undefined) { |
| 43 | + detach(node); |
| 44 | + insertAfter(this.start, node); |
| 45 | + return node.val; |
| 46 | + } else { |
| 47 | + return -1; |
| 48 | + } |
| 49 | +}; |
| 50 | + |
| 51 | +/** |
| 52 | + * @param {number} key |
| 53 | + * @param {number} value |
| 54 | + * @return {void} |
| 55 | + */ |
| 56 | +LRUCache.prototype.put = function(key, value) { |
| 57 | + let node = this.map[key]; |
| 58 | + if (!node) { |
| 59 | + if (this.count == this.capacity) { |
| 60 | + // deleting last nodes |
| 61 | + let t = this.end.pre; |
| 62 | + detach(t); |
| 63 | + delete this.map[t.key]; |
| 64 | + } else { |
| 65 | + this.count++; |
| 66 | + } |
| 67 | + node = new Node(key, value); |
| 68 | + this.map[key] = node; |
| 69 | + insertAfter(this.start, node); |
| 70 | + } else { |
| 71 | + node.val = value; |
| 72 | + detach(node); |
| 73 | + insertAfter(this.start, node); |
| 74 | + } |
| 75 | +}; |
| 76 | + |
| 77 | +/** |
| 78 | + * Your LRUCache object will be instantiated and called as such: |
| 79 | + * var obj = Object.create(LRUCache).createNew(capacity) |
| 80 | + * var param_1 = obj.get(key) |
| 81 | + * obj.put(key,value) |
| 82 | + */ |
0 commit comments