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:
schedule
andschedule[i]
are lists with lengths in range[1, 50]
.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 };