[LeetCode] Meeting Rooms

简介: Problem Description: Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],.

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 };

 

目录
相关文章
LeetCode 841:钥匙和房间 Keys and Rooms
题目: ​ 有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。 ​ 在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。
682 0
|
C++
[LeetCode] Best Meeting Point
Problem Description: A group of two or more people wants to meet and minimize the total travel distance.
925 0
[LeetCode] Meeting Rooms II
Problem Description: Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],.
925 0
|
4天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
4天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
12 0
|
4天前
|
算法
【刷题】 leetcode 面试题 08.05.递归乘法
递归算法是一种在计算机科学和数学中广泛应用的解决问题的方法,其基本思想是利用问题的自我相似性,即将一个大问题分解为一个或多个相同或相似的小问题来解决。递归算法的核心在于函数(或过程)能够直接或间接地调用自身来求解问题的不同部分,直到达到基本情况(也称为基础案例或终止条件),这时可以直接得出答案而不必再进行递归调用。
25 4
【刷题】 leetcode 面试题 08.05.递归乘法