forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMy Calendar II.py
93 lines (86 loc) · 3.19 KB
/
My Calendar II.py
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
class Node:
def __init__(self, start, end, val):
self.start = start
self.end = end
self.val = val
self.left = None
self.right = None
def insertable(self, node):
if node.end <= node.start:
return True
if node.end <= self.start:
if not self.left:
return True
else:
return self.left.insertable(node)
elif node.start >= self.end:
if not self.right:
return True
else:
return self.right.insertable(node)
else:
if self.val == 1:
leftS = min(self.start, node.start)
leftE = max(self.start, node.start)
rightS = min(self.end, node.end)
rightE = max(self.end, node.end)
if not self.left and not self.right:
return True
elif not self.left:
return self.right.insertable(Node(rightS, rightE, 1))
elif not self.right:
return self.left.insertable(Node(leftS, leftE, 1))
else:
resL = self.left.insertable(Node(leftS, leftE, 1))
resR = self.right.insertable(Node(rightS, rightE, 1))
if resL and resR:
return True
return False
else:
return False
def insert(self, node):
if node.end <= node.start:
return
if node.end <= self.start:
if not self.left:
self.left = node
else:
self.left.insert(node)
elif node.start >= self.end:
if not self.right:
self.right = node
else:
self.right.insert(node)
else:
leftS = min(self.start, node.start)
leftE = max(self.start, node.start)
rightS = min(self.end, node.end)
rightE = max(self.end, node.end)
self.val += 1
self.start, self.end = leftE, rightS
if not self.left and not self.right:
self.left = Node(leftS, leftE, 1) if leftS < leftE else None
self.right = Node(rightS, rightE, 1) if rightS < rightE else None
elif not self.left:
self.left = Node(leftS, leftE, 1) if leftS < leftE else None
self.right.insert(Node(rightS, rightE, 1))
elif not self.right:
self.right = Node(rightS, rightE, 1) if rightS < rightE else None
self.left.insert(Node(leftS, leftE, 1))
else:
self.left.insert(Node(leftS, leftE, 1))
self.right.insert(Node(rightS, rightE, 1))
return
class MyCalendarTwo:
def __init__(self):
self.root = None
def book(self, start: int, end: int) -> bool:
if not self.root:
self.root = Node(start, end, 1)
return True
else:
newNode = Node(start, end, 1)
if self.root.insertable(newNode):
self.root.insert(newNode)
return True
return False