且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Meeting Rooms 会议室

更新时间:2022-09-17 22:59:49

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.

这道题给了我们一堆会议的时间,问我们能不能同时参见所有的会议,这实际上就是求区间是否有交集的问题,我们可以先给所有区间排个序,用起始时间的先后来排,然后我们从第二个区间开始,如果开始时间早于前一个区间的结束时间,则说明会议时间有冲突,返回false,遍历完成后没有冲突,则返回true,参见代码如下:

class Solution {
public:
    bool canAttendMeetings(vector<Interval>& intervals) {
        sort(intervals.begin(), intervals.end(), [](const Interval &a, const Interval &b){return a.start < b.start;});
        for (int i = 1; i < intervals.size(); ++i) {
            if (intervals[i].start < intervals[i - 1].end) {
                return false;
            }
        }
        return true;
    }
};

本文转自博客园Grandyang的博客,原文链接:会议室[LeetCode] Meeting Rooms ,如需转载请自行联系原博主。