[LeetCode] Meeting Rooms 會議室

weixin_34234823發表於2017-12-15

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 ,如需轉載請自行聯絡原博主。

相關文章