当前位置:   article > 正文

[Leetcode] 759. Employee Free Time 员工空闲时间

[Leetcode] 759. Employee Free Time 员工空闲时间

网上看到这篇文章,这里记录巩固一下。

题目

  1. You are given a list schedule of employees,which represents the working time for each
  2. employee.Each employee has a list of non-overlapping Intervals,and these intervals are
  3. in sorted order.Return the list of finite intervals representing common,positive-length
  4. free for all employees,alse in sorted order.
  5. Example 1:
  6. Input: schedule=[[[1,2],[5,6]],[[1,3]],[[4,10]]]
  7. Output:[[3,4]]
  8. Explanation:
  9. There are a total of three employees, and all common
  10. free time intervals would be [-inf, 1], [3, 4], [10, inf].
  11. We discard any intervals that contain inf as they aren't finite.
  12. Example 2:
  13. Input: schedule=[[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
  14. Output:[[5,6],[7,9]]

题目大意:
    给定一组员工的工作时间,其中每个员工的工作时间是一组排好序的不相交的区间,要求输出所有员工都空闲的区间,不包含首尾的无限区间.


解题

      先拆分一维数组,然后进行排序(以start进行排序,若相等则以end排序,从小到大),最后枚举各个区间看是否重叠.

在这里插入图片描述

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5. struct Interval{
  6. int start;
  7. int end;
  8. Interval():start(0),end(0){}
  9. Interval(int s,int e):start(s),end(e){}
  10. };
  11. // class MyCompare{
  12. // public:
  13. // bool operator()(const Interval& a,const Interval& b){
  14. // return a.start==b.start?(a.end<b.end):(a.start<b.start);
  15. // }
  16. // };
  17. class Solution{
  18. public:
  19. vector<Interval> employeeFreeTime(vector<vector<Interval>>& schedule){
  20. vector<Interval> board;
  21. for(auto& sch:schedule){
  22. for(auto& i:sch){
  23. board.push_back(i);
  24. }
  25. }
  26. //sort(board.begin(),board.end(),MyCompare());
  27. sort(board.begin(),board.end(),[](const Interval& a,const Interval& b){
  28. if(a.start==b.start){
  29. return a.end<b.end;
  30. }
  31. return a.start<b.start;
  32. });
  33. if(board.size()==1) return vector<Interval>{};
  34. vector<Interval> ans;
  35. int i=1,L=board[0].end;
  36. while(i<board.size()){
  37. if(board[i].start<=L){
  38. L=max(board[i].end,L);
  39. }else{
  40. ans.push_back({L,board[i].start});
  41. L=board[i].end;
  42. }
  43. i++;
  44. }
  45. // for(auto& an:board){
  46. // cout<<"["<<an.start<<","<<an.end<<"]";
  47. // }
  48. // cout<<endl;
  49. // for(auto& an:ans){
  50. // cout<<"["<<an.start<<","<<an.end<<"]";
  51. // }
  52. return ans;
  53. }
  54. };
  55. int main(int argc,char* argv[]){
  56. vector<vector<Interval>> schedule={{{1,2},{5,6}},{{1,3}},{{4,10}}};//{{{1,3},{6,7}},{{2,4}},{{2,5},{9,12}}};
  57. vector<Interval> ans=Solution().employeeFreeTime(schedule);
  58. for(auto& an:ans){
  59. cout<<"["<<an.start<<","<<an.end<<"]";
  60. }
  61. cout<<endl;
  62. return 0;
  63. }

参考: 

LeetCode:输出所有员工都空闲的区间_求所有员工的空闲实际_路上的追梦人的博客-CSDN博客

leetcode:759. 员工空闲时间_员工空闲时间 牛客_OceanStar的学习笔记的博客-CSDN博客

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号