博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Meeting Rooms II
阅读量:5900 次
发布时间:2019-06-19

本文共 2627 字,大约阅读时间需要 8 分钟。

Problem Description:

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.

For example,

Given [[0, 30],[5, 10],[15, 20]],
return 2.


The idea is to group those non-overlapping meetings in the same room and then count how many rooms we need. You may refer to .

The code is as follows.

1 class Solution { 2 public: 3     int minMeetingRooms(vector
& intervals) { 4 sort(intervals.begin(), intervals.end(), compare); 5 vector
> rooms; 6 int n = intervals.size(); 7 for (int i = 0; i < n; i++) { 8 int idx = findNonOverlapping(rooms, intervals[i]); 9 if (rooms.empty() || idx == -1)10 rooms.push_back({intervals[i]});11 else rooms[idx].push_back(intervals[i]);12 }13 return (int)rooms.size();14 }15 private:16 static bool compare(Interval& interval1, Interval& interval2) {17 return interval1.start < interval2.start;18 }19 int findNonOverlapping(vector
>& rooms, Interval& interval) {20 int n = rooms.size();21 for (int i = 0; i < n; i++)22 if (interval.start >= rooms[i].back().end)23 return i;24 return -1;25 }26 };

Update: for each group of non-overlapping intervals, we just need to store the last added one instead of the full list. So we could use a vector<Interval> instead of vector<vector<Interval>> in C++. The code is now as follows.

1 class Solution {  2 public: 3     int minMeetingRooms(vector
& intervals) { 4 sort(intervals.begin(), intervals.end(), compare); 5 vector
rooms; 6 int n = intervals.size(); 7 for (int i = 0; i < n; i++) { 8 int idx = findNonOverlapping(rooms, intervals[i]); 9 if (rooms.empty() || idx == -1)10 rooms.push_back(intervals[i]);11 else rooms[idx] = intervals[i];12 }13 return (int)rooms.size();14 } 15 private:16 static bool compare(Interval& interval1, Interval& interval2) {17 return interval1.start < interval2.start;18 }19 int findNonOverlapping(vector
& rooms, Interval& interval) {20 int n = rooms.size();21 for (int i = 0; i < n; i++)22 if (interval.start >= rooms[i].end)23 return i;24 return -1;25 }26 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4713099.html

你可能感兴趣的文章
【博客话题】毕业——开始人生的艰苦历程
查看>>
Linux安装telnet
查看>>
sap scriptfom 多语言翻译
查看>>
黄聪:3分钟学会sessionStorage用法
查看>>
Entity Framework 全面教程详解(转)
查看>>
Windows上Python2.7安装Scrapy过程
查看>>
Chapter 3:Code Style in Django
查看>>
挖掘数据金矿 领军协同创新 曙光荣膺“2016大数据创新应用领袖企业”称号
查看>>
Fast通道获得Win10 Mobile Build 14977更新
查看>>
《BackTrack 5 Cookbook中文版——渗透测试实用技巧荟萃》—第3章3.6节识别操作系统...
查看>>
linux系统防火墙iptables命令规则及配置的示例
查看>>
10 个顶尖的 Linux 开源人工智能工具
查看>>
Firefox 跟踪保护技术将页面加载时间减少 44%
查看>>
聚合(根)、实体、值对象精炼思考总结
查看>>
java解析虾米音乐
查看>>
rails将类常量重构到数据库对应的表中之三
查看>>
mysql 多行合并函数
查看>>
【案例】RAID卡写策略改变引发的问题
查看>>
第四十八讲:tapestry 与 淘宝kissy editor编辑器带图片上传
查看>>
Linux/Centos 重置Mysql root用户密码
查看>>