-
Notifications
You must be signed in to change notification settings - Fork 14
/
MyCalendarTwo.java
127 lines (97 loc) · 3.25 KB
/
MyCalendarTwo.java
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package leetcode.segmenttree;
public class MyCalendarTwo {
public static void main(String[] args) {
MyCalendarTwo calendar = new MyCalendarTwo();
System.out.println(calendar.book(10, 20));
System.out.println(calendar.book(50, 60));
System.out.println(calendar.book(10, 40));
System.out.println(calendar.book(5, 15));
System.out.println(calendar.book(5, 10));
System.out.println(calendar.book(25, 55));
}
SegmentTree segmentTree;
public MyCalendarTwo() {
segmentTree = new SegmentTree();
}
public boolean book(int start, int end) {
if (segmentTree.query(1, 1, (int) 1e9 + 1, start + 1, end) >= 2) {
return false;
}
segmentTree.update(1, 1, (int) 1e9 + 1, start + 1, end);
return true;
}
static class SegmentTree {
static class Node {
int left;
int right;
int val;
int add;
}
Node[] tree;
int count;
public SegmentTree() {
count = 1;
tree = new Node[(int) 5e6 + 1];
tree[count++] = new Node();
}
public int query(int pos, int left, int right, int l, int r) {
if (l <= left && right <= r) {
return tree[pos].val;
}
lazyCreate(pos);
pushDown(pos);
int res = 0;
int mid = left + right >> 1;
if (l <= mid) {
res = Math.max(res, query(tree[pos].left, left, mid, l, r));
}
if (r > mid) {
res = Math.max(res, query(tree[pos].right, mid + 1, right, l, r));
}
return res;
}
public void update(int pos, int left, int right, int l, int r) {
if (l <= left && right <= r) {
tree[pos].val += 1;
tree[pos].add += 1;
return;
}
lazyCreate(pos);
pushDown(pos);
int mid = left + right >> 1;
if (l <= mid) {
update(tree[pos].left, left, mid, l, r);
}
if (r > mid) {
update(tree[pos].right, mid + 1, right, l, r);
}
pushUp(pos);
}
private void pushUp(int pos) {
tree[pos].val = Math.max(tree[tree[pos].left].val, tree[tree[pos].right].val);
}
private void pushDown(int pos) {
if (tree[pos].left != 0 && tree[pos].right != 0 && tree[pos].add != 0) {
int add = tree[pos].add;
tree[tree[pos].left].val += add;
tree[tree[pos].left].add += add;
tree[tree[pos].right].val += add;
tree[tree[pos].right].add += add;
tree[pos].add = 0;
}
}
private void lazyCreate(int pos) {
if (tree[pos] == null) {
tree[pos] = new Node();
}
if (tree[pos].left == 0) {
tree[pos].left = count++;
tree[tree[pos].left] = new Node();
}
if (tree[pos].right == 0) {
tree[pos].right = count++;
tree[tree[pos].right] = new Node();
}
}
}
}