|
| 1 | +/** |
| 2 | + * 1206. Design Skiplist |
| 3 | + * https://leetcode.com/problems/design-skiplist/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Design a Skiplist without using any built-in libraries. |
| 7 | + * |
| 8 | + * A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with |
| 9 | + * treap and red-black tree which has the same function and performance, the code length of Skiplist |
| 10 | + * can be comparatively short and the idea behind Skiplists is just simple linked lists. |
| 11 | + * |
| 12 | + * For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into |
| 13 | + * it. The Skiplist works this way: |
| 14 | + * |
| 15 | + * You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the |
| 16 | + * help of the top layers, add, erase and search can be faster than O(n). It can be proven that the |
| 17 | + * average time complexity for each operation is O(log(n)) and space complexity is O(n). |
| 18 | + * |
| 19 | + * See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list |
| 20 | + * Implement the Skiplist class: |
| 21 | + * - Skiplist() Initializes the object of the skiplist. |
| 22 | + * - bool search(int target) Returns true if the integer target exists in the Skiplist or false |
| 23 | + * otherwise. |
| 24 | + * - void add(int num) Inserts the value num into the SkipList. |
| 25 | + * - bool erase(int num) Removes the value num from the Skiplist and returns true. If num does not |
| 26 | + * exist in the Skiplist, do nothing and return false. If there exist multiple num values, |
| 27 | + * removing any one of them is fine. |
| 28 | + */ |
| 29 | + |
| 30 | +var Skiplist = function() { |
| 31 | + this.values = {}; |
| 32 | +}; |
| 33 | + |
| 34 | +/** |
| 35 | + * @param {number} target |
| 36 | + * @return {boolean} |
| 37 | + */ |
| 38 | +Skiplist.prototype.search = function(target) { |
| 39 | + return target in this.values; |
| 40 | +}; |
| 41 | + |
| 42 | +/** |
| 43 | + * @param {number} num |
| 44 | + * @return {void} |
| 45 | + */ |
| 46 | +Skiplist.prototype.add = function(num) { |
| 47 | + this.values[num] = (this.values[num] ?? 0) + 1; |
| 48 | +}; |
| 49 | + |
| 50 | +/** |
| 51 | + * @param {number} num |
| 52 | + * @return {boolean} |
| 53 | + */ |
| 54 | +Skiplist.prototype.erase = function(num) { |
| 55 | + if (!(num in this.values)) { |
| 56 | + return false; |
| 57 | + } |
| 58 | + if (!--this.values[num]) { |
| 59 | + delete this.values[num]; |
| 60 | + } |
| 61 | + return true; |
| 62 | +}; |
0 commit comments