-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1206.design-skiplist.java
More file actions
100 lines (90 loc) · 2.53 KB
/
1206.design-skiplist.java
File metadata and controls
100 lines (90 loc) · 2.53 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
99
100
#
# @lc app=leetcode id=1206 lang=java
#
# [1206] Design Skiplist
#
# @lc code=start
class Skiplist {
private static final int MAX_LEVEL = 16;
private Node head;
private int maxLevel;
private static class Node {
int val;
Node[] forward;
Node(int val, int level) {
this.val = val;
forward = new Node[level];
}
}
private int randomLevel() {
int level = 1;
while (Math.random() < 0.25 && level < MAX_LEVEL) {
++level;
}
return level;
}
public Skiplist() {
head = new Node(-1, MAX_LEVEL);
maxLevel = 1;
}
public boolean search(int target) {
Node cur = head;
for (int i = maxLevel - 1; i >= 0; --i) {
while (cur.forward[i] != null && cur.forward[i].val < target) {
cur = cur.forward[i];
}
}
cur = cur.forward[0];
return cur != null && cur.val == target;
}
public void add(int num) {
Node[] update = new Node[MAX_LEVEL];
Node cur = head;
for (int i = maxLevel - 1; i >= 0; --i) {
while (cur.forward[i] != null && cur.forward[i].val < num) {
cur = cur.forward[i];
}
update[i] = cur;
}
int level = randomLevel();
if (level > maxLevel) {
for (int i = maxLevel; i < level; ++i) {
update[i] = head;
}
maxLevel = level;
}
Node newNode = new Node(num, level);
for (int i = 0; i < level; ++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 cur = head;
for (int i = maxLevel - 1; i >= 0; --i) {
while (cur.forward[i] != null && cur.forward[i].val < num) {
cur = cur.forward[i];
}
update[i] = cur;
}
Node cand = update[0].forward[0];
if (cand == null || cand.val != num) {
return false;
}
for (int i = 0; i < maxLevel; ++i) {
if (update[i].forward[i] == cand) {
update[i].forward[i] = cand.forward[i];
}
}
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