|
| 1 | +class Node { |
| 2 | + constructor(key = '', cnt = 0) { |
| 3 | + this.prev = null; |
| 4 | + this.next = null; |
| 5 | + this.cnt = cnt; |
| 6 | + this.keys = new Set([key]); |
| 7 | + } |
| 8 | + |
| 9 | + insert(node) { |
| 10 | + node.prev = this; |
| 11 | + node.next = this.next; |
| 12 | + this.next.prev = node; |
| 13 | + this.next = node; |
| 14 | + return node; |
| 15 | + } |
| 16 | + |
| 17 | + remove() { |
| 18 | + this.prev.next = this.next; |
| 19 | + this.next.prev = this.prev; |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +var AllOne = function() { |
| 24 | + this.root = new Node(); |
| 25 | + this.root.next = this.root; |
| 26 | + this.root.prev = this.root; |
| 27 | + this.nodes = {}; |
| 28 | +}; |
| 29 | + |
| 30 | +AllOne.prototype.inc = function(key) { |
| 31 | + const root = this.root; |
| 32 | + const nodes = this.nodes; |
| 33 | + |
| 34 | + if (!nodes[key]) { |
| 35 | + if (root.next === root || root.next.cnt > 1) { |
| 36 | + nodes[key] = root.insert(new Node(key, 1)); |
| 37 | + } else { |
| 38 | + root.next.keys.add(key); |
| 39 | + nodes[key] = root.next; |
| 40 | + } |
| 41 | + } else { |
| 42 | + const curr = nodes[key]; |
| 43 | + const next = curr.next; |
| 44 | + |
| 45 | + if (next === root || next.cnt > curr.cnt + 1) { |
| 46 | + nodes[key] = curr.insert(new Node(key, curr.cnt + 1)); |
| 47 | + } else { |
| 48 | + next.keys.add(key); |
| 49 | + nodes[key] = next; |
| 50 | + } |
| 51 | + |
| 52 | + curr.keys.delete(key); |
| 53 | + if (curr.keys.size === 0) { |
| 54 | + curr.remove(); |
| 55 | + } |
| 56 | + } |
| 57 | +}; |
| 58 | + |
| 59 | +AllOne.prototype.dec = function(key) { |
| 60 | + const root = this.root; |
| 61 | + const nodes = this.nodes; |
| 62 | + const curr = nodes[key]; |
| 63 | + |
| 64 | + if (curr.cnt === 1) { |
| 65 | + delete nodes[key]; |
| 66 | + } else { |
| 67 | + const prev = curr.prev; |
| 68 | + |
| 69 | + if (prev === root || prev.cnt < curr.cnt - 1) { |
| 70 | + nodes[key] = prev.insert(new Node(key, curr.cnt - 1)); |
| 71 | + } else { |
| 72 | + prev.keys.add(key); |
| 73 | + nodes[key] = prev; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + curr.keys.delete(key); |
| 78 | + if (curr.keys.size === 0) { |
| 79 | + curr.remove(); |
| 80 | + } |
| 81 | +}; |
| 82 | + |
| 83 | +AllOne.prototype.getMaxKey = function() { |
| 84 | + return this.root.prev === this.root ? '' : Array.from(this.root.prev.keys)[0]; |
| 85 | +}; |
| 86 | + |
| 87 | +AllOne.prototype.getMinKey = function() { |
| 88 | + return this.root.next === this.root ? '' : Array.from(this.root.next.keys)[0]; |
| 89 | +}; |
| 90 | + |
| 91 | +/** |
| 92 | + * Your AllOne object will be instantiated and called as such: |
| 93 | + * var obj = new AllOne() |
| 94 | + * obj.inc(key) |
| 95 | + * obj.dec(key) |
| 96 | + * var param_3 = obj.getMaxKey() |
| 97 | + * var param_4 = obj.getMinKey() |
| 98 | + */ |
0 commit comments