Skip to content

Commit be89665

Browse files
committed
Time: 11 ms (61.38%), Space: 19.3 MB (6.9%) - LeetHub
1 parent ec8f6be commit be89665

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# time complexity: O(nlogn)
2+
# space complexity: O(n)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:
8+
n = len(intervals)
9+
if n == 0:
10+
return 0
11+
intervals.sort(key=lambda x: (x[1], x[0]))
12+
result = []
13+
result.append(intervals[0][1] - 1)
14+
result.append(intervals[0][1])
15+
for i in range(1, n):
16+
start = intervals[i][0]
17+
end = intervals[i][1]
18+
last = result[-1]
19+
secLast = result[-2]
20+
if start > last:
21+
result.append(end - 1)
22+
result.append(end)
23+
elif start == last:
24+
result.append(end)
25+
elif start > secLast:
26+
result.append(end)
27+
return len(result)
28+
29+
30+
intervals = [[1, 3], [3, 7], [8, 9]]
31+
print(Solution().intersectionSizeTwo(intervals))
32+
intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
33+
print(Solution().intersectionSizeTwo(intervals))
34+
intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
35+
print(Solution().intersectionSizeTwo(intervals))

0 commit comments

Comments
 (0)