Skip to content

Commit 9a2f6f3

Browse files
authored
Create 1206-design-skiplist.js
1 parent 724be38 commit 9a2f6f3

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

1206-design-skiplist.js

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
const Skiplist = function () {
2+
this.maxLvl = ~~Math.log2(20000)
3+
this.levels = [...Array(this.maxLvl)].map(() => new Node(-1))
4+
for (let i = this.maxLvl - 1; i > 0; i--) {
5+
this.levels[i].down = this.levels[i - 1]
6+
}
7+
this.head = this.levels[this.maxLvl - 1]
8+
}
9+
10+
/**
11+
* @param {number} target
12+
* @return {boolean}
13+
*/
14+
Skiplist.prototype.search = function (target) {
15+
const pre = this.iter(target)
16+
return !pre[0].next ? false : pre[0].next.val === target
17+
}
18+
19+
Skiplist.prototype.iter = function (target) {
20+
let cur = this.head
21+
const pre = []
22+
for (let i = this.maxLvl - 1; i >= 0; i--) {
23+
while (cur.next && cur.next.val < target) cur = cur.next
24+
pre[i] = cur
25+
cur = cur.down
26+
}
27+
return pre
28+
}
29+
30+
/**
31+
* @param {number} num
32+
* @return {void}
33+
*/
34+
Skiplist.prototype.add = function (num) {
35+
const pre = this.iter(num)
36+
const lvs = decideLevels(this.maxLvl)
37+
for (let i = 0; i < lvs; i++) {
38+
const next = pre[i].next
39+
pre[i].next = new Node(num)
40+
pre[i].next.next = next
41+
if (i > 0) pre[i].next.down = pre[i - 1].next
42+
}
43+
}
44+
45+
/**
46+
* @param {number} num
47+
* @return {boolean}
48+
*/
49+
Skiplist.prototype.erase = function (num) {
50+
const pre = this.iter(num)
51+
let ret
52+
if (!pre[0].next || pre[0].next.val !== num) return false
53+
for (let i = this.maxLvl - 1; i >= 0; i--) {
54+
if (pre[i].next && pre[i].next.val === num) {
55+
const toBeDeleted = pre[i].next
56+
pre[i].next = toBeDeleted.next
57+
toBeDeleted.next = null
58+
toBeDeleted.down = null
59+
}
60+
}
61+
return true
62+
}
63+
64+
/**
65+
* Your Skiplist object will be instantiated and called as such:
66+
* var obj = new Skiplist()
67+
* var param_1 = obj.search(target)
68+
* obj.add(num)
69+
* var param_3 = obj.erase(num)
70+
*/
71+
72+
const decideLevels = (max) => {
73+
let ans = 1
74+
while (Math.random() > 0.5 && ans < max) ans++
75+
return ans
76+
}
77+
78+
const Node = function (val) {
79+
this.val = val
80+
this.next = null
81+
this.down = null
82+
}

0 commit comments

Comments
 (0)