Catalogue
Range
370. Range Addition
Trade off for Update and Query!
- O(1) for update and O(n) for Query
- O(n) for update and O(1) for Query
- We only care about the intervals start and end!!!
1 | class Solution(object): |
Overlap
- How to define two intervals overapped?
- A.end > B.start
- B.end > A.start
- Why we always sort by start or end at first?
252. Meeting Rooms
1
2
3
4
5
6
7class Solution:
def canAttendMeetings(self, intervals):
intervals.sort(key=lambda x:x.start)
for i in range(1, len(intervals)):
if intervals[i].start < intervals[i-1].end:
return False
return True
253. Meeting Rooms II
1 | class Solution(object): |
- Follow Up : Return Max Overlapped Interval
Operations
56. Merge Intervals
1 | # Definition for an interval. |
57. Insert Interval
- O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Solution(object):
def insert(self, intervals, newInterval):
n = len(intervals)
res = []
i = 0
while i < n and newInterval.start > intervals[i].end:
res.append(intervals[i])
i += 1
while i < n and intervals[i].start <= newInterval.end:
newInterval.start = min(intervals[i].start, newInterval.start)
newInterval.end = max(intervals[i].end, newInterval.end)
i += 1
res.append(newInterval)
while i < n:
res.append(intervals[i])
i += 1
return res