forked from DVampire/LeetCodePro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1206.design-skiplist.java
More file actions
98 lines (90 loc) · 2.58 KB
/
1206.design-skiplist.java
File metadata and controls
98 lines (90 loc) · 2.58 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#
# @lc app=leetcode id=1206 lang=java
#
# [1206] Design Skiplist
#
# @lc code=start
import java.util.Random;
class Skiplist {
static final int MAX_LEVEL = 16;
static final double P = 0.5;
final Node head = new Node(-1, MAX_LEVEL);
int level = 1;
Random rand = new Random();
static class Node {
int val;
Node[] forward;
Node(int val, int level) {
this.val = val;
this.forward = new Node[level];
}
}
public Skiplist() {}
private int randomLevel() {
int lvl = 1;
while (lvl < MAX_LEVEL && rand.nextDouble() < P) {
lvl++;
}
return lvl;
}
public boolean search(int target) {
Node curr = head;
for (int i = level - 1; i >= 0; --i) {
while (curr.forward[i] != null && curr.forward[i].val < target) {
curr = curr.forward[i];
}
}
curr = curr.forward[0];
return curr != null && curr.val == target;
}
public void add(int num) {
Node[] update = new Node[MAX_LEVEL];
Node curr = head;
for (int i = level - 1; i >= 0; --i) {
while (curr.forward[i] != null && curr.forward[i].val < num) {
curr = curr.forward[i];
}
update[i] = curr;
}
int lvl = randomLevel();
if (lvl > level) {
for (int i = level; i < lvl; ++i) {
update[i] = head;
}
level = lvl;
}
Node newNode = new Node(num, lvl);
for (int i = 0; i < lvl; ++i) {
newNode.forward[i] = update[i].forward[i];
update[i].forward[i] = newNode;
}
}
public boolean erase(int num) {
Node[] update = new Node[MAX_LEVEL];
Node curr = head;
for (int i = level - 1; i >= 0; --i) {
while (curr.forward[i] != null && curr.forward[i].val < num) {
curr = curr.forward[i];
}
update[i] = curr;
}
curr = curr.forward[0];
if (curr == null || curr.val != num) return false;
for (int i = 0; i < level; ++i) {
if (update[i].forward[i] != curr) break;
update[i].forward[i] = curr.forward[i];
}
while (level > 1 && head.forward[level - 1] == null) {
level--;
}
return true;
}
}
/**
* Your Skiplist object will be instantiated and called as such:
* Skiplist obj = new Skiplist();
* boolean param_1 = obj.search(target);
* obj.add(num);
* boolean param_3 = obj.erase(num);
*/
# @lc code=end