跳到主要内容

Employee Free Time

描述​

We are given a list schedule of employees, which represents the working time for each employee.

Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.

Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.

(Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.

Example 1:

Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]

Output: [[3,4]]

Explanation: There are a total of three employees, and all common free time intervals would be [-inf, 1], [3, 4], [10, inf]. We discard any intervals that contain inf as they aren't finite.

Example 2:

Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]

Output: [[5,6],[7,9]]

Constraints:

  • 1≤schedule.length,schedule[i].length≤501 \leq schedule.length, schedule[i].length \leq 50
  • 0≤schedule[i].start<schedule[i].end≤1080 \leq schedule[i].start < schedule[i].end \leq 10^8

分析​

这题求的是区间之间的空白段,跟 Merge Intervals是反过来的,所以可以直接复用 Merge Intervals 的代码,然后取反即可。

代码​

# Employee Free Time
# 时间复杂度O(n),空间复杂度O(1)
class Solution:
def employeeFreeTime(self, schedule):
intervals = []
for employee_schedule in schedule:
intervals.extend(employee_schedule)
merged = self.merge(intervals)
result = []
for i in range(len(merged) - 1):
result.append(Interval(merged[i].end, merged[i + 1].start))
return result

def merge(self, intervals):
result = []
for interval in intervals:
self.insert(result, interval)
return result

def insert(self, intervals, newInterval):
i = 0
while i < len(intervals):
cur = intervals[i]
if newInterval.end < cur.start:
intervals.insert(i, newInterval)
return intervals
elif newInterval.start > cur.end:
i += 1
continue
else:
newInterval.start = min(newInterval.start, cur.start)
newInterval.end = max(newInterval.end, cur.end)
intervals.pop(i)
intervals.append(newInterval)
return intervals

相关题目​