Leetcode 759. Employee Free Time

Problem:

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.

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]]

(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.

Note:

  1. schedule and schedule[i] are lists with lengths in range [1, 50].
  2. 0 <= schedule[i].start < schedule[i].end <= 10^8.

Solution:

  这道题简单说说,Hard题中的easy题,index数组记录了每一位员工正要处理的事物的索引,初始化为0。用一个优先级队列,队列顶端是所有员工在处理的事物中开始时间最早的那个员工的编号和事务。用timestamp记录了所有当前进行的事务中最迟的结束时间,如果下一个开始最早的事务的开始时间比当前最迟的结束时间还大,则推入结果集中,否则更新最迟的结束时间。

Code:

 1 /**
 2  * Definition for an interval.
 3  * struct Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() : start(0), end(0) {}
 7  *     Interval(int s, int e) : start(s), end(e) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     struct mycmp{
13         bool operator()(pair<int,Interval> &p1,pair<int,Interval> &p2){
14             return p1.second.start > p2.second.start;
15         }
16     };
17     vector<Interval> employeeFreeTime(vector<vector<Interval>>& schedule) {
18         vector<Interval> result;
19         vector<int> index(schedule.size(),1);
20         priority_queue<pair<int,Interval>,vector<pair<int,Interval>>,mycmp> pq;
21         for(int i = 0;i != schedule.size();++i)
22             pq.push(make_pair(i,schedule[i][0]));
23         int timestamp = pq.top().second.end;
24         while(!pq.empty()){
25             pair<int,Interval> top = pq.top();
26             if(top.second.start > timestamp){
27                 Interval interval(timestamp,top.second.start);
28                 result.push_back(interval);
29                 timestamp = top.second.end;
30             }
31             else{
32                 timestamp = max(timestamp,top.second.end);
33             }
34             pq.pop();
35             if(index[top.first] != schedule[top.first].size()){
36                 pq.push(make_pair(top.first,schedule[top.first][index[top.first]]));
37                 index[top.first]++;
38             }
39         }
40         return result;
41     }
42 };

猜你喜欢

转载自www.cnblogs.com/haoweizh/p/10262619.html
今日推荐