[LeetCode] Meeting Rooms

Problem Description:

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.

For example,
Given [[0, 30],[5, 10],[15, 20]],
return false


The idea is pretty simple: first we sort the intervals in the ascending order of start; then we check for the overlapping of each pair of neighboring intervals. If they do, then return false; after we finish all the checks and have not returned false, just return true.

Sorting takes O(nlogn) time and the overlapping checks take O(n) time, so this idea isO(nlogn) time in total.

The code is as follows.

 1 class Solution {
 2 public:
 3     bool canAttendMeetings(vector<Interval>& intervals) {
 4         sort(intervals.begin(), intervals.end(), compare);
 5         int n = intervals.size();
 6         for (int i = 0; i < n - 1; i++)
 7             if (overlap(intervals[i], intervals[i + 1]))
 8                 return false;
 9         return true;
10     }
11 private:
12     static bool compare(Interval& interval1, Interval& interval2) {
13         return interval1.start < interval2.start;
14     }
15     bool overlap(Interval& interval1, Interval& interval2) {
16         return interval1.end > interval2.start;
17     } 
18 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值